Dave Ceddia
Dave Ceddia

Reputation: 1490

Memory leak with AJAX requests + jQuery

I am repeatedly fetching a JSON object from the server with AJAX calls. Over time, the memory usage of the browser grows (tried with Chrome, Safari, Firefox). Using Chrome's heap snapshots, I've discovered that the timestamp strings are being left around with no references. If I a take a sequence of snapshots, I see the number of Strings is continually increasing.

$(function() {
    var latestTimestamp = 0;

    function fetchData() {
        $.get("/parameter?format=json&since=" + latestTimestamp, gotData)
    }   

    function gotData(data) {
        latestTimestamp = data['timestamp'];
        setTimeout(fetchData, 250);
    }   

    fetchData();
});

Other notes:

Upvotes: 6

Views: 2230

Answers (3)

Humayoo
Humayoo

Reputation: 690

Did you try cleartimeout javascript function ? if not please try this.

var abc=null;
function gotData(data) {
latestTimestamp = data['timestamp'];
data=null;
clearTimeout(abc);
abc=setTimeout(fetchData, 250);
}

Upvotes: 1

Jakub Konecki
Jakub Konecki

Reputation: 46018

I believe this problem lies with jQuery and/or browsers. I've seen similar leak with often AJAX calls.

Instead of polling the server 4 times a second consider pushing data from server to client. I don't know what platform you're using, but if it's .Net you might want to take a look at SignalR

https://github.com/SignalR/SignalR

http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx

Upvotes: 0

David Gorsline
David Gorsline

Reputation: 5018

Once you're done with data[], you can get rid of it:

function gotData(data) {
    latestTimestamp = data['timestamp'];
    delete data;
    setTimeout(fetchData, 250);
} 

Upvotes: 0

Related Questions