Javascript callback recursion

From EggeWiki
Jump to navigation Jump to search

Recently, I had the misfortune to have to write some JavaScript which needed to work in IE6. Basically, I wanted to create a loading screen for a web page. Basically the code looks like:

 <script type="text/javascript">
 var urls = [
 function loadResources()
   update(currentStep + '/' + progressbar_steps);
     var url = urls[currentStep];
     var req = GetXmlHttpObject();
     update('loading ' + url);"GET", url, true);
     req.onreadystatechange = getUpdateState(req, url);
   } else {
     window.location = 'welcome.htm';
 function getUpdateState(req, url) {
   return function() {
     var state = req.readyState;
     if (state != 4) { return; }
     req = null;
     setTimeout('loadResources()', 0); // This is the magic line to get it to work under IE6!
 </script></head><body onload="javascript: loadResources();">

LoadResource would register a callback to getUpdateState, which would in turn call LoadResource again until all the resources had been loaded. Under IE6, a varying number of URLs would get loaded. Once I added the setTimeout function, it worked fine under IE6. I guess IE must have just been growing the stack on each callback, and eventually had a stack overflow of some type. I wouldn't get a script error when this would happen, rather the loading would just stop.