javascript 仅在选项卡处于活动状态时运行 setTimeout
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5766263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run setTimeout only when tab is active
提问by Kyle
Is there a way to stop setTimeout("myfunction()",10000);
from counting up when the page isn't active. For instance,
有没有办法setTimeout("myfunction()",10000);
在页面不活动时停止计数。例如,
- A user arrives at a "some page" and stays there for 2000ms
- User goes to another tab, leaves "some page" open.
myfunction()
doesn't fire until they've come back for another 8000ms.
- 用户到达“某个页面”并在那里停留 2000 毫秒
- 用户转到另一个选项卡,打开“某个页面”。
myfunction()
直到它们再返回 8000 毫秒后才会触发。
回答by ?ime Vidas
(function() {
var time = 10000,
delta = 100,
tid;
tid = setInterval(function() {
if ( document.hidden ) { return; }
time -= delta;
if ( time <= 0 ) {
clearInterval(tid);
myFunction(); // time passed - do your work
}
}, delta);
})();
Live demo:https://jsbin.com/xaxodaw/quiet
现场演示:https : //jsbin.com/xaxodaw/quiet
Changelog:
变更日志:
- June 9, 2019: I've switched to using
document.hidden
to detect when the page is not visible.
- 2019 年 6 月 9 日:我已切换到使用
document.hidden
来检测页面何时不可见。
回答by Jasuten
Great answer by ?ime Vidas, it helped me with my own coding. For completeness sake I made an example for if you want to use setTimeout instead of setInterval:
?ime Vidas 的出色回答,它帮助我完成了自己的编码。为了完整起见,我举了一个例子,如果你想使用 setTimeout 而不是 setInterval:
(function() {
function myFunction() {
if(window.blurred) {
setTimeout(myFunction, 100);
return;
}
// What you normally want to happen
setTimeout(myFunction, 10000);
};
setTimeout(myFunction, 10000);
window.onblur = function() {window.blurred = true;};
window.onfocus = function() {window.blurred = false;};
})();
You'll see that the window blurred check has a shorter time set than normal, so you can set this depending on how soon you require the rest of the function to be run when the window regains focus.
您会看到窗口模糊检查设置的时间比正常时间短,因此您可以根据需要在窗口重新获得焦点时运行其余函数的时间来设置它。
回答by PetersenDidIt
You can do something like:
您可以执行以下操作:
$([window, document]).blur(function() {
// Clear timeout here
}).focus(function() {
// start timeout back up here
});
Window is for IE, document is for the rest of the browser world.
窗口适用于 IE,文档适用于浏览器世界的其余部分。
回答by Pointy
What you'd have to do is set up a mechanism to set timeouts at small intervals, keeping track of total elapsed time. You'd also track "mouseenter" and "mouseleave" on the whole page (the <body>
or something). When the short-term timeouts expire, they can check the window state (in or out) and not restart the process when the window is not in focus. The "mouseenter" handler would start all paused timers.
您需要做的是设置一种机制,以小间隔设置超时,跟踪总经过时间。您还可以在整个页面(<body>
或其他内容)上跟踪“mouseenter”和“mouseleave” 。当短期超时到期时,他们可以检查窗口状态(进入或退出),并且在窗口未处于焦点时不会重新启动进程。“mouseenter”处理程序将启动所有暂停的计时器。
edit— @?ime Vidas has posted an excellent example.
编辑——@?ime Vidas 发布了一个很好的例子。
回答by BroFox
I use almost the same approach as ?ime Vidas in my slider
but my code is based on document.visibilityState
for page visibility checking:
我在滑块中使用与 ?ime Vidas 几乎相同的方法,但我的代码基于document.visibilityState
页面可见性检查:
var interval = 4000;
function slideshow() {
// slideshow code
};
$(document).ready(function() {
var switchInterval;
function intervalHandler() {
switchInterval = setInterval(function() {
if (document.visibilityState === "visible") {
slideshow();
} else {
return;
}
}, interval);
}
intervalHandler();
});
- About Page Visibility API: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
回答by Caumons
I've finally implemented a variation of @?ime Vidas' answer, because the interval was still running if I opened another program and the browser window was not visible, but the page executing the interval was the active browser tab. So, I've modified the condition to document.hidden || !document.hasFocus()
. This way, if the document is hidden or the document doesn't have the focus, the interval function just returns.
我终于实现了@?ime Vidas 答案的变体,因为如果我打开另一个程序并且浏览器窗口不可见,间隔仍在运行,但执行间隔的页面是活动的浏览器选项卡。因此,我已将条件修改为document.hidden || !document.hasFocus()
. 这样,如果文档被隐藏或文档没有焦点,间隔函数就会返回。
(function() {
var time = 10000,
delta = 100,
tid;
tid = setInterval(function() {
if ( document.hidden || !document.hasFocus() ) { return; }
time -= delta;
if ( time <= 0 ) {
clearInterval(tid);
myFunction(); // time passed - do your work
}
}, delta);
})();