在我的代码中,我遇到了这样的情况:
var t = setInterval(function(e) {
if (document.hasFocus()) {
// Tab Has Focus so,
// Execute some actions
}
},4000);
我有一个jQuery间隔,每4秒执行一些操作。像动画对象一样,并向我的DOM添加css类。
问题在于,当我更改标签('模糊'窗口事件)然后重新添加焦点事件时,重新执行。
是否有方法让当前操作完成然后停止间隔,然后在页面聚焦时恢复?
答案 0 :(得分:1)
一点google around会有所帮助,但这就是我找到的
var t = setInterval(function(e) {
if (document.hasFocus()) {
// Tab Has Focus so,
// Execute some actions
} else {
// if not in focus
// stop the interval
clearInterval(t);
}
},4000);
答案 1 :(得分:1)
好吧,没有你的全部代码。我不能给你一个确切的解决方案。 所以,这可能不是你正在寻找的。 但它有一个类似的概念。 甚至可能比你真正需要的更多:
var i = 0; // Track the iteration we are currently in.
var t; // Used to set and clear intervals.
function timer() {
t = setInterval(function(e) {
// Whereas I keep track of Iterations, you may wanna keep track of specific styles, etc...
console.log(i);
localStorage.setItem('currentIteration', i);
i++;
},1000);}
timer();
$(window).focus(function() {
// If localStorage is set, continue from where we left off.
var currentIteration = localStorage.getItem('currentIteration');
if ( currentIteration != "" ) {
i = ( Number(currentIteration) + 1 );
}
timer();
});
$(window).blur(function() {
// You could command the css application to finish on tab leave.
// Although, it should already finish, since it's a function already in progress.
clearInterval(t);
});