Javascript setInterval“赶上”页面最小化/消失后
我有一个非常正常的 setInterval
调用(我认为):
var myInterval = setInterval("myFunction('passVar1', 'passedVar2')", 8000);
如果我在页面上,它会完美运行,但如果我让页面打开一段时间(或最小化它?),当我回来时,就像它只是将所有 myFunction 调用构建到一个队列中,并尝试快速运行它们以“赶上”。然后,当它恢复正常时,它会再次像预期的那样以 8 秒的间隔运行。
我做错了什么吗?我现在使用的是 Firefox 5——如果这与它有什么关系的话。想法? TIA。
I have a pretty normal setInterval
call (I think):
var myInterval = setInterval("myFunction('passVar1', 'passedVar2')", 8000);
It runs perfectly if I'm on the page, but if I leave the page open for awhile (or minimize it?), when I come back, it's like it just built up all the myFunction calls into a queue and tries to run through them all really fast to "catch up". Then, when it catches back up, it runs at 8 seconds apart again like it's supposed to.
Am I doing something wrong? I'm using Firefox 5 at the moment - if that has anything to do with it. Thoughts? TIA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一方面,修复您的
setInterval
,使其不使用 eval:其次,这取决于浏览器间隔执行或不执行的操作。
更新:
根据下面的评论和这里的相关聊天讨论是使用
setTimeout
的小提琴:http://jsfiddle.net/maniator/VR7WE/
更新:
根据进一步的讨论,事实证明jquery 的动画存在问题
以下小提琴仅在动画完成时运行超时: http://jsfiddle.net/maniator/c869Z/5/
For one thing fix your
setInterval
so it doesnt use eval:Second, it depends on the browser what the interval does or does not do.
UPDATE:
Based on comments below and the related chat discussion here is a fiddle using
setTimeout
:http://jsfiddle.net/maniator/VR7WE/
UPDATE:
Based on further discussion, turns out it was an issue with jquery's animate
The following fiddle only runs the timeout when the animate is done: http://jsfiddle.net/maniator/c869Z/5/
您可以使用“setTimeout()”驱动您自己的间隔机制,这将使您的代码适应实际的浏览器行为。您可能会做一些事情来跟踪“目标”时间,当您错过目标时,下一次超时将相应地小于标称延迟。这样,即使您的标称延迟为 100 毫秒,并且浏览器每 1000 毫秒才给您一次控制权,您在任何时候都只会有一个待处理的超时。当焦点返回时,您的代码会注意到事情恢复正常并几乎自动恢复较高频率的活动。
You can drive your own interval mechanism with "setTimeout()", and that will allow your code to adapt to the actual browser behavior. You'd probably do something to keep track of "target" times, and when you miss the target the next timeout would be correspondingly smaller than the nominal delay. That way, even if your nominal delay was 100ms and the browser were only giving you control every 1000ms, you'd only have one pending timeout at any time. When focus returns, your code would then notice things getting back to normal and resume the higher-frequency activity pretty much automatically.