I've noticed in a couple of JavaScript libraries that make use of setInterval
, that the library will bind an event listener to the window
's unload
event, so as to clear all the created intervals using clearInterval
.
One example is History.js which keeps a "List of intervals set, to be cleared when document is unloaded".
Snippet:
// ====================================================================
// Interval record
/**
* History.intervalList
* List of intervals set, to be cleared when document is unloaded.
*/
History.intervalList = [];
/**
* History.clearAllIntervals
* Clears all setInterval instances.
*/
History.clearAllIntervals = function(){
var i, il = History.intervalList;
if (typeof il !== "undefined" && il !== null) {
for (i = 0; i < il.length; i++) {
clearInterval(il[i]);
}
History.intervalList = null;
}
};
The event listener that calls this function on the unload
event is added here.
Snippet:
/**
* Clear Intervals on exit to prevent memory leaks
*/
History.Adapter.bind(window,"unload",History.clearAllIntervals);
So, my question is, why do some JavaScript authors do this? It seems like these intervals will be cleared automatically when the browsers leaves the page (I've never seen it do otherwise). Is there an advantage to doing this? Does it compensate for a browser bug of some kind? If so, what bug and which browsers does it affect?
As mentioned in the comments, this code was added to History.js for compatibility with Env.js.
Env.js is a headless browser written in JavaScript that is no longer under active development. So this is definitely an edge-case, to say the least. I'm guessing this issue is caused by a limitation of JavaScript itself.
User Lance Leonard has pointed out in the comments that there is a possible memory leak issue in IE 10.
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