setInterval - How to fire only once?

2020-04-05 12:05发布

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);
}

2条回答
劫难
2楼-- · 2020-04-05 12:30

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.

查看更多
ら.Afraid
3楼-- · 2020-04-05 12:31

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.

查看更多
登录 后发表回答