William Entriken
William Entriken

Reputation: 39333

Why does this javascript refresh leak memory?

I have a dashboard on my TV and the page needs to refresh every second.

At the bottom of the page I have:

function startRefresh() {
    $.get('', function(data) {
        var newDoc = document.open("text/html", "replace");
        newDoc.write(data);
        newDoc.close();
    });
}
$(function() {
    setTimeout(startRefresh,1000);
});

This works great, except that each page load causes the memory usage to go up as reported by chrome://memory-redirect/.

Is there a way to fix this? I am not interested to create a separate page for a DIV and just reloading that part.

FYI http header refresh and document.location = document.location both produced unusable flickering

Upvotes: 4

Views: 1258

Answers (1)

floribon
floribon

Reputation: 19193

If you are using Chrome, you should use the "Timeline" to record the memory usage. Launch the timeline, then wait for the page to refresh a few times, and then stop the timeline and have a look at the results. If you see the line keeping increasing, that means your objects in memory (or the DOM nodes) are never released and garbage collected.

I have never used document.open/write myself so I do not know if that can cause issues with garbage collection, but I suspect it does.

If your detect clearly a memory lak using the Timeline, then open the "Profiles" tab and take a Heat snapshot before and after a page reload, then use "comparison" to see what have changed and how much bigger your memory impact is. If for instance your old compiled code (or obejct references) is still there, plus the new one, then it explains your leak.

Upvotes: 0

Related Questions