Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval - How to fire only once?

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);
}
like image 717
Stan Avatar asked Mar 16 '12 17:03

Stan


People also ask

How do I make setInterval run only once?

The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using clearInterval() . If you wish to have your function called once after the specified delay, use setTimeout() .

How can I stop setInterval after 10 seconds?

To stop it after running a set number of times, just add a counter to the interval, then when it reached that number clear it.

How do I terminate setInterval?

If you set the return value of setInterval to a variable, you can use clearInterval to stop it.

Does setInterval fire right away?

This property can be used in the callback of the setInterval() function, as it would get immediately executed once and then the actual setInterval() with this function will start after the specified delay.


1 Answers

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.

like image 145
Simon Edström Avatar answered Sep 28 '22 17:09

Simon Edström