setInterval 会导致浏览器挂起吗?
几年前,我被警告不要长时间使用 setInterval
,因为如果被调用的函数运行时间超过指定的时间间隔,它可能会导致浏览器挂起,然后无法捕获up:
setInterval( function(){
foo = 'bar_' + i++;
}, 1 );
现在,我知道在循环中添加大量代码可能会导致浏览器挂起无论如何,并且会阻止诸如alert
、prompt<之类的代码/code> 和
confirm
会停止代码的运行,但是有什么充分的理由避免 setInterval
吗?
注意:我知道如何进行递归 setTimeout
调用(因为这就是我一直在使用的),这个问题是我试图弄清楚它是否仍然值得使用它们,或者是否 setInterval
可以安全使用。
A couple years ago I was warned against using setInterval
for long periods of time as it supposedly would cause the browser to hang if the called function ran longer than the designated interval, and would then not be able to catch up:
setInterval( function(){
foo = 'bar_' + i++;
}, 1 );
Now, I'm aware that adding lots of code in a loop could cause the browser to hang anyway, and that blocking code like alert
, prompt
, and confirm
will stop the code in it's tracks, but is there any good reason to avoid setInterval
?
Note: I am aware of how to do recursive setTimeout
calls (as that's what I've been using), this question is my trying to figure out if it's still worth using them, or whether setInterval
can be used safely.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
setInterval
不好的原因是它会尝试每 X MS 执行一次代码,而不管线程中发生了什么。因此,如果您有:...您可能会在
setInterval
自己的代码完成之前尝试重新执行多次!但是,您可以类似地使用setTimeout
并避免此问题:...现在
complexFunction
只会在其自己的代码完成后再次调用自身,因此如果其自己的代码需要更长的时间完成时间少于 1 MS,您不会像使用setInterval
那样需要处理任何积压工作The reason
setInterval
is bad is because it will try to execute the code every X MS regardless of what's going on in the thread. So if you have:...you may end up with
setInterval
trying to re-execute several times before even its own code is complete! However, you can usesetTimeout
similarly and avoid this problem:...now
complexFunction
will only call itself again once its own code is complete, so if its own code takes longer than 1 MS to complete you won't have any backlog to deal with like you would withsetInterval
在循环中使用 setTimeout 总是更好,这样您就可以准确地知道何时继续计时:
否则正如您上面所说,浏览器将不得不
赶上
,并且由于您的循环处于无限状态,因此可能不会。it always better to use setTimeout in a loop so you know exactly when to continue timing:
otherwise as you said above, the browser will have to
catch up
and since ur loop is in infinitum, it might not.