Pao*_*edi 7 javascript settimeout
我使用了这段代码(后跟一个填充"tcap"textarea的xmlhttprequest):
st=setTimeout(checkme(),4000)
Run Code Online (Sandbox Code Playgroud)
在哪里checkme():
function checkme() {
if (typeof (st) != 'undefined') clearTimeout(st)
if (document.getElementById("tcap").innerHTML.length > 0) {
document.getElementById('waitmsg').style.display = 'none'
} else {
st = setTimeout(checkme(), 1000)
}
}
Run Code Online (Sandbox Code Playgroud)
如果我运行它,它冻结Firefox 19没有错误消息.但是如果我用第一个参数替换(在代码和checkme()函数中):
st=setTimeout(function(){checkme()},4000)
Run Code Online (Sandbox Code Playgroud)
它工作正常.所以我的问题是:checkme()使用或不使用anon函数调用函数有什么区别?为什么在第一种情况下会冻结Firefox?
谢谢
Jon*_*øgh 12
你需要删除parens
st=setTimeout(checkme(),4000)
Run Code Online (Sandbox Code Playgroud)
所以与其:
st=setTimeout(checkme,4000)
Run Code Online (Sandbox Code Playgroud)
否则,立即调用该函数.
由于checkme函数中存在相同的错误,因此无限递归可能会导致浏览器死亡.
setTimeout接受函数作为参数,将函数作为参数传递的正确方法是将其定义为匿名函数,或者仅提供函数名称.如果使用括号(括号),则实际上并未传递函数:您正在执行函数并将函数的结果传递给setTimeout.
因此,在setTimeout中指定函数时,以及在需要将函数作为参数传递的任何其他位置时,不应使用括号.
| 归档时间: |
|
| 查看次数: |
5277 次 |
| 最近记录: |