Does the browser keep track of active setInterval
and setTimeout
IDs? Or is this solely up to the developer to keep track of?
If it does keep track of them, is it accessible via the BOM?
Does the browser keep track of active setInterval
and setTimeout
IDs? Or is this solely up to the developer to keep track of?
If it does keep track of them, is it accessible via the BOM?
This may interest you, if you are curious about how the timer is 'remembered' by its window.
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title>Timer </title>
</head>
<body>
<h1>Timers</h1>
<script>
if(!window.timers){
var timers= [], i= 0;
while(i<5){
timers.push(setInterval(function(){
if(confirm(timers.join('\n')+'\nRemove a timer?')){
clearInterval(timers.shift());
}
},
i*1000+1000));
++i;
}
}
</script>
</body>
</html>
Look at the scripts below, the browser could remember the id of each setTimeout iteration
for (i = 1; i <= d; i++) {
(function(j) {
var delay = j/d;
t[j] = setTimeout(function() {
elem.style.top = j+"px";
},delay);
})(i);
}
You can access them by
for (i in t) {
alert(t[i]);
}
It is up for the developer to keep track of. You can do so by using the returned value of the setTimeout/setInterval function and passing that value to the clearTimeout/clearInterval function - as described in other answers here.
This appears to be because each browser will implement keeping track of the intervals in their own way.
From w3.org/TR/2009/WD-html5-20090212/no.html (a draft, but w3schools and http://w3.org/TR/Window explain it almost the same way) - setTimeout and setInterval return a long and clearTimeout/clearInterval accept a long to find and cancel