我无法确定这段代码有什么问题。它在 chrome 中运行一次然后崩溃然后运行等等。无法在 Firefox 和 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>
我是否遗漏了 javascript 中的重要内容?我做错了什么??
更新 代码在以下浏览器中运行:Chrome 14.08 - Safari 5.1 它还将按预期在 JsFiddle.net 中运行。 它会工作但在 Chrome 5.0 中反复崩溃 当它必须在以下浏览器中运行包含 SyncRunner.wait() 的函数时停止 - 没有发出任何错误:Firefox 3.6 - IE 9 - Opera 10.61
更新 2 在对 Narenda 提供的答案进行一些调查后,似乎 FF 4 及以后的版本在这里遇到了麻烦。但我不知道其他浏览器的根本原因。 所以问题是在非 webkit 浏览器中使用 document.write() 将 document.write() 替换为以下函数,它现在应该可以工作了:
function print( message ) {
var loc = document.getElementById( 'logpanel' );
var tag = document.createElement('li');
if( message != undefined ){
tag.appendChild( document.createTextNode( message ) );
loc.appendChild( tag );
}
}
我仍然想知道其他浏览器出了什么问题 谢谢
最佳答案
我得到了错误
'attempt to run compile-and-go script on a cleared scope'
当我在 firefox 中运行它时。当它尝试在 AsyncRunner.wait
中调用 fn()
时会发生这种情况。
看起来这是 firefox 4 及更高版本中的错误。看看这些相关的 SO 问题
Error: Attempt to run compile-and-go script on a cleared scope (特别是最后一个答案谈到使用 document.write
)和
jQuery Animation error = attempt to run compile-and-go script on a cleared scope
我无法在 chrome 上重现该程序的崩溃。
关于javascript - 与定时器异步运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7792302/