当页面/浏览器失去焦点时暂停 setInterval
我在客户的主页上制作了一个简单的幻灯片,使用 setInterval 来计时轮换。
为了防止浏览器在页面未处于焦点时(正在查看另一个选项卡或另一个程序)搞砸 setInterval,我使用:
function onBlur() {
clearInterval(play);
};
function onFocus() {
mySlideRotateFunction();
};
if (/*@cc_on!@*/false) {
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
其中 mySlideRotateFunction 设置 setInterval 并运行一些 jQuery。虽然这在大多数情况下都有效,但我发现有时 onBlur 似乎没有运行,当我返回页面时,计时已经“建立”并且旋转变得疯狂。
我无法完全确定为什么这种情况偶尔会发生,而在其他情况下却不会发生。
我的问题 - 我的代码有问题吗?当浏览器窗口失去焦点时,是否有人对“暂停”setInterval有更好的建议?
谢谢
I have a simple slideshow that I've made on a client's homepage, using setInterval to time the rotations.
To prevent browsers from screwing up setInterval when the page isn't in focus (another tab is being viewed, or another programme), I'm using:
function onBlur() {
clearInterval(play);
};
function onFocus() {
mySlideRotateFunction();
};
if (/*@cc_on!@*/false) {
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
Where mySlideRotateFunction sets the setInterval and runs some jQuery. While this works the majority of the time, I find that, on occasion, it appears as though onBlur hasn't run, and when I return to the page the timings have 'built up' and the rotations go crazy.
I can't quite determine a cause as to why this happens on occasion, and not on others.
My question- is there a problem with my code, and does anyone have a better suggestion for 'pausing' setInterval when browser window is out of focus?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
立即在
setInterval
内检查文档是否获得焦点。该间隔将像往常一样继续触发,但其中的代码仅在文档获得焦点时才会执行。如果窗口模糊并随后重新聚焦,则间隔将继续保持时间,但在此期间document.hasFocus()
为false
,因此浏览器无需当焦点恢复时,通过多次执行代码块来“赶上”。Immediately inside
setInterval
, place a check to see if the document is focused. The interval will continue firing as usual, but the code inside will only execute if the document is focused. If the window is blurred and later refocused, the interval will have continued keeping time butdocument.hasFocus()
wasfalse
during that time, so there's no need for the browser to "catch up" by executing the code block a bunch of times when focus is restored.尝试这样的事情:
在 IE9 和 FF6 中完成的一些测试
Try something like this:
Some testing done in IE9 and FF6
有一个使用 Web Workers 的 setInterval 实现,它可以防止浏览器主线程暂停间隔的常见行为。
很酷的是你只需要导入你想要的包并且语法保持不变。他们负责使用网络工作人员触发间隔的底层逻辑。
Github 页面
Npm 包
There is an implementation of setInterval using web workers which prevent common behavior with the browser's main thread pausing the interval.
Cool thing is you just need to import the packages you want and the syntax stays the same. They took care of the underlying logic to use web workers to fire intervals.
Github page
Npm package