[英]How to start javascript setinterval once cleared?
我有一个setinterval每5秒运行一次。 这在页面加载时效果很好。
我有以下几种情况:
注意,这里所有的内容加载(例如页面加载)都是通过ajax调用完成的。
我的代码:
初始化 :
$.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function() {
$.automation.tanks.tableInit();
});
绑定功能:
bindIntervalEvent: function (target, url, callback) {
$(window)
.on("focus.mine",
function() {
$.automation.worker.setUpdateInterval(target, url, callback);
})
.on("blur",
function() {
$.automation.worker.stopUpdateInterval();
}).trigger("focus.mine");
}
间隔函数:
setUpdateInterval: function (target, url, callback) {
if ($.automation.globals.globalInterval.value.length === 0) {
$.automation.globals.globalInterval.value.push(window.setInterval(
function () {
var options = {
loadTarget: target
}
$.automation.worker.getView(url,
function() {
if (callback)
callback();
},
options);
},
5000));
}
}
停止时间间隔的功能:
stopUpdateInterval: function () {
if ($.automation.globals.globalInterval.value.length === 0)
return;
console.log("deleting");
for (var i = 0; i <= $.automation.globals.globalInterval.value.length; i++) {
window.clearInterval($.automation.globals.globalInterval.value[i])
$.automation.globals.globalInterval.value.splice(i, 1);
console.log($.automation.globals.globalInterval.value.length);
}
}
当停止间隔时,我也删除了窗口绑定:
unBindIntervalEvent: function() {
$(window).off("focus.mine");
$(window).unbind("blur");
}
返回步骤3:
我的getview函数回调中的成功方法与我在开始代码中执行的方法相同:
$(".updatelatest")
.on("click",
function () {
var _this = $(this);
var options = {
loadTarget:"#TanksContent"
}
$.automation.worker.getView("/Tank/GetTanks",
function (data) {
$(_this).switchClass("col-md-5", "col-md-1", 1000, function() {
$(_this).addClass("hidden");
$(".search").switchClass("col-md-5", "col-md-12", 1000, "easeInOutQuad");
})
$.automation.tanks.tableInit();
$.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function () {
$.automation.tanks.tableInit();
});
$(window).trigger("blur");
}, options);
});
但这不会开始间隔。 它显然已初始化,因为它在执行window.blur时(例如,当我更改tab时)有效,但由于某种原因,它无法正常工作。
我试图触发Windows模糊事件,但没有任何反应,我试图触发自定义窗口事件“ focuse.mine”,但没有任何反应。
我在开发过程中没有注意到这一点,因为我已经打开了萤火虫,并且每次我检查脚本,css或控制台时,都会执行模糊功能,因此我以为我的代码可以按预期工作,但是现在部署它时,我注意到了这一点。
我的头跳动得超出理智,我无法弄清楚哪里出了问题。
好吧,这很有趣。 我只是发现在调用setUpdateInterval()时发现了这一点。 直接功能它给了我想要的结果。
我意识到,像我一样将它们拆分的原因在于模糊事件。 当用户返回页面时,将触发“ Focus.mine”以再次启动间隔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.