When a user clicks a nav button on my site they call a .load()
, i.e., $("#main_window").load("file.php");
If file.php contains JavaScript along with a setInterval
timer then if a user clicks the nav button multiple times they'll create multiple setInterval
s. How do I stop this and only have one timer at all times?
Obtaining the ID of the timer doesn't help because .load
resets global variables. Thus I'm unable to prevent multiple timers on repeated .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 output: with two .loads()
:
undefined
27
undefined
34