Javascript callback recursion
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.