当我的网站打开多个选项卡时,为什么 setTimeout 会加速?
我有一个每秒倒计时的计时器。 它工作得很好,直到用户打开我的网站的 3 或 4 个选项卡,此时最新选项卡的计时器速度变为两倍或三倍。 我目前只能在 IE8 中重现该错误。 我之前使用的是 setInterval,并且也可以在 Firefox 中重现该错误。
我实际上使用的是 FBJS(Facebook 的 Javascript),所以我只给出一些伪代码。
function countDown() {
...
setTimeout(function() { countDown() }, 1000);
}
countDown();
然而,我真正寻找的是更多的理论。 我知道浏览器可以尝试使用 setInterval 来“追赶”,但是多个选项卡如何导致 setTimeout 出现这种行为?
I have a timer that counts down every second. It works great until the user opens up 3 or 4 tabs of the my site, at which point the newest tab's timer goes double or triple speed. I can currently only reproduce the bug in IE8. I was previously using setInterval, and could reproduce the bug in Firefox as well.
I'm actually using FBJS (Facebook's Javascript), so I'll just give some pseudocode.
function countDown() {
...
setTimeout(function() { countDown() }, 1000);
}
countDown();
However, what I'm really looking for is more theoretical. I know browsers can try and play "catch up" with setInterval, but how can multiple tabs cause this behaviour for setTimeout?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
整个情况非常奇怪。 我想到的唯一有意义的场景是浏览器试图“平滑”自我恢复 setTimeouts 的周期,与 setInterval 相同,而这样做的代码实际上混淆了不同窗口中的计时器其他。
我不知道这是否可行,尤其是涉及 Facebook,但一个有趣的测试是为每个实例赋予
countDown
函数一个随机名称,看看这是否有任何区别,例如:改变了观察到的行为,这支持了我想到的场景。 (并且可能提供解决问题的方法。)
That whole situation is very odd. The only scenario that's coming to mind where it makes any sense is one where the browser is trying to "smooth" the period of self-reinstating setTimeouts, same as for setInterval, and the code that's doing that actually confuses timers in different windows with each other.
I don't know if it's feasible, especially with Facebook involved, but an interesting test would be to give each instance a randomized name for the
countDown
function and see if that makes any difference, like:If this changes the observed behavior, that argues for the scenario I have in mind. (And possibly provides a way of addressing the problem.)