I have an application using JavaScript's setInterval()
to run a digital clock. I was wondering if it has a timeout, or limit, to the amount of times it can execute this function.
I have an application using JavaScript's setInterval()
to run a digital clock. I was wondering if it has a timeout, or limit, to the amount of times it can execute this function.
- You mean how many times the callback will be executed? No, there is no limit. Why was this question downvoted? – davin Commented Oct 20, 2011 at 14:58
3 Answers
Reset to default 37setInterval()
will run infinitely.
If you wish to terminate the 'loop' you can use clearInterval. For example:
var counter = 0;
var looper = setInterval(function(){
counter++;
console.log("Counter is: " + counter);
if (counter >= 5)
{
clearInterval(looper);
}
}, 1000);
No, the given function will keep being executed until you clear the interval manually with clearInterval()
Note that in most browsers, your function will still be executed when the page is in a background tab, but mobile browsers (notably IOS5 Safari) may free the page until its focused / visible again.
As others have mentioned, there is not limit to the number of times your interval will run, however if you intend to run a timer indefinitely you should consider the info here:
Minimum setInterval()/setTimeout() delay on background tabs
If your user is likely to tab-out, 1 second seems to be safe minimum interval