I'm having trouble figuring what's wrong with this piece of code. It runs once in chrome then crashes then runs and so on. It can't run in firefox and IE.
<html>
<head>
<title> Async Module Runner </title>
<script type="text/javascript">
var TestRunner = (function(){
var queue = [];
var paused = false;
return {
run : function( fn ) {
queue.push(fn);
if( queue.length > 0 && paused != true && queue[0] != undefined ) {
queue.shift()();
}
},
pause : function(){
paused = true;
},
resume : function(){
paused = false;
this.run();
}
};
})();
var AsyncRunner = {};
AsyncRunner.wait = function( fn, time ) {
TestRunner.pause();
setTimeout(function(){
fn();
TestRunner.resume();
}, time);
};
var Test = {
setUp : function(){
document.write('yep! <br />');
},
tearDown : function(){
document.write('yep yep <br />');
},
testAsync1 : function(){
AsyncRunner.wait( function(){ document.write('okay! <br />'); }, 3000 );
},
testAsync2 : function(){
AsyncRunner.wait( function(){ document.write('okay again <br />'); }, 2000 );
},
testAsync3 : function(){
AsyncRunner.wait( function(){ document.write('okay again and again!! <br />'); }, 5000 );
}
};
window.onload = function(){
for( var i in Test ) {
TestRunner.run(Test[i]);
}
};
</script>
</head>
<body>
</body>
</html>
Am i missing something important in javascript? what am i doing wrong??
UPDATE The code runs in the following browsers: Chrome 14.08 - Safari 5.1 It will also run in JsFiddle.net as expected. It will work but crash repeatedly in Chrome 5.0 It stops when it has to run functions containing SyncRunner.wait() in the following browsers - without issuing any error : Firefox 3.6 - IE 9 - Opera 10.61
UPDATE 2 After a little bit investigation with the answer provided by Narenda, it seems FF 4 and onwards are having trouble here. But i don't the underlying reason with other browsers. So the problem is using document.write() in non-webkit browsers Replace document.write() with the following function and it should work by now:
function print( message ) {
var loc = document.getElementById( 'logpanel' );
var tag = document.createElement('li');
if( message != undefined ){
tag.appendChild( document.createTextNode( message ) );
loc.appendChild( tag );
}
}
I'm still interested in know what went wrong with other browsers Thanks