当用户单击我网站上的导航按钮时,他们将调用.load()
,即$("#main_window").load("file.php");
。如果file.php包含JavaScript和setInterval
计时器,则用户单击导航按钮多次,它们将创建多个setInterval
。我该如何停止并且始终只有一个计时器?
获取计时器的ID无济于事,因为.load
会重置全局变量。因此,我无法防止在重复的.load()
上使用多个计时器。
var myVar;
console.log(myVar); // will be undefined when .load() calls this file again.
myVar = setInterval(reload, 5000);
console.log(myVar); // A new ID will be created on each .load(), but all old instances will continue to fire
function reload() {
$(tableName).DataTable().ajax.reload(null, false);
console.log("reloaded");
}
Console.log输出:具有两个.loads()
:
未定义
27
未定义
34
答案 0 :(得分:0)
if(myVar){
clearInterval(myVar)
}
var myVar;
console.log(myVar); // will be undefined when .load() calls this file again.
myVar = setInterval(reload, 5000);
console.log(myVar); // A new ID will be created on each .load(), but all old instances will continue to fire
function reload() {
$(tableName).DataTable().ajax.reload(null, false);
console.log("reloaded");
}