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?
Timer functions are implemented by browsers and their implementations will be different among different browsers. Timers are also implemented natively by the Node. js runtime itself.
setTimeout and setInterval are not actually included in javascript - let's understand this. Maybe you think setTimeout like this -: The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
In JavaScript, a timer is created to execute a task or any function at a particular time. Basically, the timer is used to delay the execution of the program or to execute the JavaScript code in a regular time interval. With the help of timer, we can delay the execution of the code.
The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);
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
You can add such global timers tracking by overriding the setTimeout
/seInterval
functions. As a bonus you easily add code when a timer is set or popped, track live timers or popped timers, etc...
For example:
timers = {}; // pending timers will be in this variable
originalSetTimeout = window.setTimeout;
// override `setTimeout` with a function that keeps track of all timers
window.setTimeout = function(fu, t) {
var id = originalSetTimeout(function() {
console.log(id+" has timed out");
delete timers[id]; // do not track popped timers
fu();
}, t);
// track this timer in the `timers` variable
timers[id] = {id:id, setAt: new Date(), timeout: t};
console.log(id+" has been set to pop in "+t+"ms");
}
// from this point onward all uses of setTimeout will be tracked, logged to console and pending timers will be kept in the global variable "timers".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With