Javascript jQuery让tab失去焦点时完成并停止函数
在我的代码中,我遇到了如下情况:Javascript jQuery让tab失去焦点时完成并停止函数,javascript,jquery,Javascript,Jquery,在我的代码中,我遇到了如下情况: var t = setInterval(function(e) { if (document.hasFocus()) { // Tab Has Focus so, // Execute some actions } },4000); 我有一个jQuery间隔,每4秒执行一次操作。像动画对象和添加css类到我的DOM 问题是,当我更改选项卡(“模糊”窗口事件)然后重新添加焦点事件时,会重新执行 有没
var t = setInterval(function(e) {
if (document.hasFocus()) {
// Tab Has Focus so,
// Execute some actions
}
},4000);
我有一个jQuery间隔,每4秒执行一次操作。像动画对象和添加css类到我的DOM
问题是,当我更改选项卡(“模糊”窗口事件)然后重新添加焦点事件时,会重新执行
有没有一种方法可以让当前操作完成,然后停止间隔,然后在页面聚焦时恢复?稍微有点帮助,但下面是我的发现
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);
有点帮助,但这是我发现的
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);
好吧,没有你全部的代码。我不能给你一个确切的答案。 所以,这可能不是你想要的。 但它有一个相似的概念。 也许比你实际需要的还要多:
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);
});
好吧,没有你全部的代码。我不能给你一个确切的答案。 所以,这可能不是你想要的。 但它有一个相似的概念。 也许比你实际需要的还要多:
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);
});
对不起,我没有添加问题的最后一部分。当我将焦点添加到选项卡时,我还需要恢复间隔,这是一个特定的迭代次数。这些迭代是以某种方式定义的吗?没有具体的迭代次数,这是一个恒定的循环,当我在选项卡上失去焦点时,我需要停止/恢复(让他先完成当前操作),对不起,我没有添加问题的最后一部分。当我将焦点添加到选项卡时,我还需要恢复间隔,这是一个特定的迭代次数。这些迭代是以某种方式定义的吗?没有具体的迭代次数,这是一个恒定的循环,当我对某个选项卡失去焦点时,我需要停止/恢复(让他先完成当前操作),这实际上让我想起了单例模式。我喜欢你的解决方案谢谢,很高兴我能帮上忙。事实上,这让我想起了单身模式。我喜欢你的解决方案谢谢,很高兴我能帮上忙。