I have a JavaScript application that uses XMLHttpRequest to fetch and parse about 60,000 XML documents. However, IE’s memory usage grows quickly, and eventually the program crashes. I suspect this has to do with IE’s JScript GC. Below is a simplified version of my code:
Above the code, I declare two variables:
var xmlhttp;
var xmlDoc;
When the code first starts running, I set the value of xmlhttp:
xmlhttp = new XMLHttpRequest();
The script then enters the main loop:
function loadXML() {
xmlhttp.abort();
xmlhttp.open("GET", url, false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml', 'Pragma', 'no-cache');
xmlhttp.send("");
while (xmlhttp.readyState != 4) { }
xmlDoc = xmlhttp.responseXML;
setTimeout("readXML()",0);
}
function readXML() {
//Reads the XML.
//If all data has been retrieved, exit loop.
//Else, change the url and go back to loadXML()
}
Google Chrome runs the code just fine, with no errors. However, IE loops about 2000 times before crashing with an “Out of Memory” error. Is the Garbage Collector not doing it;s job? Can I rewrite my code to prevent problems?
You should not use a busy loop at all to wait for the result of an XMLHttpRequest. Also, there’s no reason to have the
xmlhttpobject public. Instead, create a new one on every call and register a callback: