JavaScript setInterval 限制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7837830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:30:00  来源:igfitidea点击:

JavaScript setInterval Limits?

javascriptsetinterval

提问by Ethan Turkeltaub

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.

我有一个使用 JavaScript 的应用程序setInterval()来运行数字时钟。我想知道它是否有超时或限制,可以执行此函数的次数。

采纳答案by Marijn

No, the given function will keep being executed until you clear the interval manually with clearInterval()

不,给定的函数将继续执行,直到您手动清除间隔 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.

请注意,在大多数浏览器中,当页面位于后台选项卡中时,您的函数仍会执行,但移动浏览器(尤其是 IOS5 Safari)可能会释放页面,直到其再次聚焦/可见。

回答by rochal

setInterval()will run infinitely.

setInterval()将无限运行。

If you wish to terminate the 'loop' you can use clearInterval. For example:

如果您希望终止“循环”,您可以使用 clearInterval。例如:

var counter = 0;

var looper = setInterval(function(){ 
    counter++;
    console.log("Counter is: " + counter);

    if (counter >= 5)
    {
        clearInterval(looper);
    }

}, 1000);

回答by Guy Cook

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

后台选项卡上的最小 setInterval()/setTimeout() 延迟

If your user is likely to tab-out, 1 second seems to be safe minimum interval

如果您的用户可能会退出,1 秒似乎是安全的最小间隔