Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • I'm using jQuery 1.7.1. EDIT: Just tried with 1.6.2 and 1.4.2, same problem.
  • The timestamp in the JSON object is actually an integer, not a string. So the accumulating strings might be temporary values?
  • Removing the + latestTimestamp from the AJAX request stops the leak.
  • A faster setTimeout (20ms) causes the leak faster. I thought the fast timeout might be to blame, so I cut it back to 250ms, but that didn't help.
like image 412
Dave Ceddia Avatar asked Nov 25 '22 00:11

Dave Ceddia


1 Answers

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);
}
like image 54
Humayoo Avatar answered Nov 27 '22 15:11

Humayoo