页面/浏览器失焦时暂停setInterval [英] Pausing setInterval when page/ browser is out of focus
问题描述
我有一个简单的幻灯片,我在客户的主页上制作,使用setInterval来计算轮换时间。
I have a simple slideshow that I've made on a client's homepage, using setInterval to time the rotations.
防止浏览器在页面时搞砸了setInterval我没有关注焦点(正在查看另一个标签或其他节目),我正在使用:
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;
}
其中mySlideRotateFunction设置setInterval并运行一些jQuery。虽然这在大多数情况下是有效的,但我发现,有时看起来似乎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.
我的问题 - 我的代码有问题,当浏览器窗口失焦时,是否有人有更好的建议'暂停'setInterval?
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?
谢谢
推荐答案
尝试这样的事情:
var myInterval;
var interval_delay = 500;
var is_interval_running = false; //Optional
$(document).ready(function () {
$(window).focus(function () {
clearInterval(myInterval); // Clearing interval if for some reason it has not been cleared yet
if (!is_interval_running) //Optional
myInterval = setInterval(interval_function, interval_delay);
}).blur(function () {
clearInterval(myInterval); // Clearing interval on window blur
is_interval_running = false; //Optional
});
});
interval_function = function () {
is_interval_running = true; //Optional
// Code running while window is in focus
}
在IE9和FF6中完成了一些测试
Some testing done in IE9 and FF6
这篇关于页面/浏览器失焦时暂停setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!