Javascript callback recursion

From EggeWiki
Revision as of 01:27, 23 March 2009 by Egge (talk | contribs) (New page: 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:...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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 = [
 "../javascript/textutils.js",
 "../javascript/x/x.js",
 "../javascript/x/x_util.js",
 "../javascript/compass.js",
 "../javascript/x/xmenu3.js",
 "../javascript/Listener.js",
 "../javascript/Clipboard.js",
 ]
 function loadResources()
 {
   update(currentStep + '/' + progressbar_steps);
   if(currentStep<progressbar_steps){
     var url = urls[currentStep];
     moveProgressBar(1);
     var req = GetXmlHttpObject();
     update('loading ' + url);
     req.open("GET", url, true);
     req.onreadystatechange = getUpdateState(req, url);
     req.send(null);
   } else {
     update('Done');
     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.