Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason to clearInterval before window unload?

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?

like image 212
Alexander O'Mara Avatar asked Dec 20 '14 23:12

Alexander O'Mara


1 Answers

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.

like image 196
Alexander O'Mara Avatar answered Oct 02 '22 23:10

Alexander O'Mara