![](/img/trans.png)
[英]Javascript setInterval/setTimeout not working when browser tab not focused
[英]jQuery - If browser tab is focused, then do AJAX - Not working
我有一个确定当前浏览器窗口或选项卡是否处于活动状态的代码。 如果处于活动状态,则选项卡的标题为“活动”,否则为“模糊”
一切正常。 这是代码:
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
document.title = 'focus';
}
}
$(this).data("prevType", e.type);
})
上面的代码工作正常。
现在,如果我向其中添加AJAX,它将无法正常工作。
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
var interval = function () {
$.ajax({
url: "<?php echo base_url('home/get') ?>",
cache: false,
success: function (html) {
$("#text").val(html);
document.title ='focus';
},
});
};
setInterval(interval, <?php echo $int ?>);
}
}
$(this).data("prevType", e.type);
})
如果聚焦,则说聚焦。 如果我没有聚焦,它会说“模糊”不到一秒钟,然后再次聚焦。 我不知道为什么 我想说的不是很模糊,那就是模糊的。 添加AJAX代码无法使其正常工作。
请帮忙。 谢谢。
您需要在blur
事件中使用clearTimeout()
。 我的代码不断轮询服务器中的数据,但是当我离开页面时,它将停止轮询。 请查看下面的实现。 我在这里的应用程序中做了类似的操作:
$(window).blur(function() {
clearTimeout(getJsonTmr);
clearTimeout(updatePreviewTmr);
}).focus(StartTimers);
function StartTimers () {
// Every half a second,
getJsonTmr = setInterval(function () {
$.get("/doodles/update?getJson&DoodleID=" + DoodleOptions.DoodleID, function (data) {
data = JSON.parse(data);
if (!DoodleOptions.isActive)
clearDoodleCanvas();
$.each(data, function (index) {
drawFromStream(data[index]);
});
});
}, 500);
updatePreviewTmr = setInterval(function () {
$.post("/doodles/update?updatePreview", {
"DoodleID": DoodleOptions.DoodleID,
"DoodlePreview": canvas.toDataURL()
});
}, 5000);
}
StartTimers();
您可以使用上面的代码作为参考并进行更改。
一个简单的参考实现为您...
function timers() {
tmrAjax = setInterval(function () {
$.get(/* ... */);
}, 1000);
}
timers();
$(window).blur(function () {
clearInterval(tmrAjax);
}).focus(timers);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.