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);
}
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() .
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.
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With