Memory leaks when using AJAX JSON call
ajax, javascript, json, memory-leaks, performance
Solution
I don't think it's the AJAX call, but the closure which is costing you memory. Your onreadystatechange function references the http object (so a reference to this will be kept with the 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've not come across closures in javascript before, they're well worth reading up on - understanding them explains a lot of behaviour which doesn't seem to make sense at first glance.
Problem
In my javascript application I have big memory leak when making `AJAX` call to retrieve `JSON` object. 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 milisecond and as you see, its synchronous call. This function costs me 1MB every 1 second. When I use instead of `AJAX` just assigning to variable like: ``` input_for_ball = JSON.parse('[0,0,0,0,0,0,0,0,0,0]'); ``` then its everything perfect. So error must be in my implementation of `AJAX` call. This happened when I use `jQuery AJAX` call too. UPDATE 12/03/2013 As `Tom van der Woerdt` mentioned below, this really was intended behavior. So as `Matt B.` suggested, I have rewrote some code to make asynchronous calls possible and it helped a lot. Now my application memory consuming is stable and small.