简体   繁体   中英

JavaScript setInterval Limits?

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.

setInterval() 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM