Memory leak when using AJAX JSON call

In my javascript application, I have a big memory leak when making an AJAX call to retrieve a JSON object. The code is really simple:

 function getNewMessage() { new_message = []; // this is global variable var input_for_ball = []; var sum; var i; var http = new XMLHttpRequest(); http.open("GET", url + "/random_ball.json", false); http.onreadystatechange = function() { if(http.readyState === 4 && http.status === 200) { var responseTxt = http.responseText; input_for_ball = JSON.parse('[' + responseTxt + ']'); } } http.send(null); new_message = input_for_ball; } 

This is called every 1 millisecond, and, as you can see, its synchronous call. This feature costs 1 MB every 1 second.

When I use AJAX instead of just assigning a variable, for example:

  input_for_ball = JSON.parse('[0,0,0,0,0,0,0,0,0,0]'); 

then all this is wonderful. So the error should be in my implementation of the AJAX call. This happened when I also used the jQuery AJAX call.

UPDATE 03/03/2013

As Tom van der Woerdt , mentioned below, it really was intended to be behavior. Since Matt B. suggested, I rewrote some code to make asynchronous calls possible, and that helped a lot. Now my application memory is stable and small.

+4
source share
1 answer

I do not think this is an AJAX call, but a closure that costs you in your memory. The onreadystatechange function refers to the http object (so a link to this will be saved with an anonymous function).

I think your code matches the pattern in example 1 in this link http://www.ibm.com/developerworks/web/library/wa-memleak/

If you have not encountered javascript closure before, they should read it - understanding them explains a lot of behavior that at first glance seems unimportant.

+3
source

All Articles