[英]How to make setInterval run when browser tab is on focus?
I have created an Interval that runs on every 2 seconds, when the page loads. 我已经创建了一个Interval,当页面加载时,它每2秒运行一次。 Now, when I move to other page, the interval is cleared (Please check the code). 现在,当我移动到其他页面时,间隔被清除(请检查代码)。 Now what I want is when I move to the same tab again, the interval should start again. 现在我想要的是当我再次移动到同一个标签时,间隔应该重新开始。
One thing I tried was that I wrote this whole code inside $(window).focus(//CODE)
but the problem is that it doesn't run when the page is initially opened in any browser's tab. 我试过的一件事是我在$(window).focus(//CODE)
编写了这整个代码,但问题是当页面最初在任何浏览器的选项卡中打开时它都不会运行。
How can solve this issue? 怎么能解决这个问题?
Here's my code: 这是我的代码:
var zzz= setInterval(anewFunc, 2000);
function anewFunc(){
$(document).ready(function(){
var chatattr=$(".chatwindow").css("visibility");
var chattitle=$("#hideid").text();
if(chatattr=="visible"){
$.ajax({
url: 'seen1.php',
type: 'post',
data: "ctitle="+chattitle,
success: function(result9){
},
error: function(){
}
});
}
$(window).blur(function(){
$.ajax({
url: 'session.php',
type: 'post',
success: function(result10){
// alert(result10);
},
error: function(){
}
});
clearInterval(zzz);
});
});
}
One thing I tried was that I wrote this whole code inside
$(window).focus(//CODE)
but the problem is that it doesn't run when the page is initially opened in any browser's tab. 我试过的一件事是我在$(window).focus(//CODE)
编写了这整个代码,但问题是当页面最初在任何浏览器的选项卡中打开时它都不会运行。
Okay, the problem here is, the setInterval()
doesn't execute at 0
seconds. 好的,这里的问题是, setInterval()
不会在0
秒执行。 It starts from 2
seconds only. 它仅从2
秒开始。 So you need to make a small change: 所以你需要做一个小改动:
ready
event, start the timer, as well as run the function for the first time. 在ready
事件内,启动计时器,并首次运行该功能。 .one()
to assign only once. 从间隔中删除事件处理程序,或仅使用.one()
分配一次。 You are repeatedly adding to the .blur()
event of window. 您正在反复添加到窗口的.blur()
事件中。 Corrected Code: 更正代码:
function anewFunc() {
var chatattr = $(".chatwindow").css("visibility");
var chattitle = $("#hideid").text();
if (chatattr == "visible") {
$.ajax({
url: 'seen1.php',
type: 'post',
data: "ctitle=" + chattitle,
success: function(result9) {},
error: function() {}
});
}
$(window).one("blur", function() {
$.ajax({
url: 'session.php',
type: 'post',
success: function(result10) {
// alert(result10);
},
error: function() {}
});
clearInterval(zzz);
});
}
$(document).ready(function() {
var zzz = setInterval(anewFunc, 2000);
anewFunc();
});
Now what I want is when I move to the same tab again, the interval should start again. 现在我想要的是当我再次移动到同一个标签时,间隔应该重新开始。
You haven't started the setInterval()
again. 您还没有再次启动setInterval()
。
$(document).ready(function () {
$(window).one("focus", function() {
var zzz = setInterval(anewFunc, 2000);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.