setInterval - How to fire only once?

喜夏-厌秋 提交于 2019-12-01 17:36:04

问题


Hello I have this snippet of code that will fire some even after time that I choose.

The problem is that if, for example I put 3 seconds it will fire every 3 seconds, what I need is it to fire only once after 3 seconds.

function playSound(timeLeft){
   var sendDataTimeout = function(){
      alert('OK');
   }
   var intervalReference = 0;
   clearInterval(intervalReference);
   intervalReference = setInterval(sendDataTimeout, timeLeft);
}

回答1:


Use setTimeout instead, it works almost the same but will only fire once. You have clearTimeout and setTimeout so its very similar to setInterval

function playSound(timeLeft){
   var sendDataTimeout = function(){
      alert('OK');
   }
   setTimeout(sendDataTimeout, timeLeft);
}

You don't have to use clearTimeout anymore. But FYI it exist and works the same as clearInterval.




回答2:


You don't need setInterval, you need setTimeout.

As the name says, setInterval fires regularly, while setTimeout fires only once. The usage is the same though.



来源:https://stackoverflow.com/questions/9741837/setinterval-how-to-fire-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!