Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery memory leak with repeated .ajax calls

I'm using the following pattern which is leaking memory in Firefox:

$(function() {

    (function() {

        var callee = arguments.callee;

        $.ajax({
            url: '...',
            success: function() { ... setTimeout(callee, 1000); },
            error: function() { ... setTimeout(callee, 1000); }
        });

    })();

});

The memory leak remains, even when success/error do nothing other than calling setTimeout again. I'm observing the leak via Windows Task Manager; if the page is left open, memory usage of firefox.exe slowly creeps up. For the final version of this code, I only need to update once a minute, but once-a-second demonstrates the memory leak much faster!

(Note: this looks like a very similar problem to this question, but the selected answer there doesn't appear to cater for Firefox)

like image 551
Bobby Jack Avatar asked Sep 01 '10 11:09

Bobby Jack


1 Answers

I was able to reproduce the problem and solved it as such:

$(function() 
{
    function checkStatus() 
    {
        $.ajax({
          url: '...',
          success: function() { ... setTimeout(checkStatus, 1000); },
          error: function() { ... setTimeout(checkStatus, 1000); }
        });

    }

    checkStatus();

});

What appears to happen is each time your anonymous method is called, it creates a variable and assigns a reference to it. Given enough time, this will fill up memory.

This solution just passes the same function ref around rather than creating a new one with each iteration.

like image 117
Matthew Avatar answered Oct 12 '22 01:10

Matthew