当我的网站打开多个选项卡时,为什么 setTimeout 会加速?

发布于 2024-07-27 23:58:41 字数 415 浏览 5 评论 0原文

我有一个每秒倒计时的计时器。 它工作得很好,直到用户打开我的网站的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫烠⑼条掵仅有一顆心 2024-08-03 23:58:41

整个情况非常奇怪。 我想到的唯一有意义的场景是浏览器试图“平滑”自我恢复 setTimeouts 的周期,与 setInterval 相同,而这样做的代码实际上混淆了不同窗口中的计时器其他。

我不知道这是否可行,尤其是涉及 Facebook,但一个有趣的测试是为每个实例赋予 countDown 函数一个随机名称,看看这是否有任何区别,例如

<?php $timerTag = rand(1, 1000); ?>
function countDown<?php echo $timerTag ?>() {
  ...
  setTimeout(function() { countDown<? php echo $timerTag ?>() }, 1000);    
}

countDown<?php echo $timerTag ?>();

:改变了观察到的行为,这支持了我想到的场景。 (并且可能提供解决问题的方法。)

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:

<?php $timerTag = rand(1, 1000); ?>
function countDown<?php echo $timerTag ?>() {
  ...
  setTimeout(function() { countDown<? php echo $timerTag ?>() }, 1000);    
}

countDown<?php echo $timerTag ?>();

If this changes the observed behavior, that argues for the scenario I have in mind. (And possibly provides a way of addressing the problem.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文