[英]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.