![](/img/trans.png)
[英]What is difference between setTimeout with function and without function ?
[英]setTimeout with or without anonymous function? What's the difference?
我使用了這段代碼(后跟一個填充“tcap”textarea的xmlhttprequest):
st=setTimeout(checkme(),4000)
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)
}
}
如果我運行它,它凍結Firefox 19沒有錯誤消息。 但是如果我用第一個參數替換(在代碼和checkme()函數中):
st=setTimeout(function(){checkme()},4000)
它工作正常。 所以我的問題是:在使用或不使用anon函數的情況下調用checkme()
函數有什么不同? 為什么在第一種情況下會凍結Firefox?
謝謝
你需要刪除parens
st=setTimeout(checkme(),4000)
所以與其:
st=setTimeout(checkme,4000)
否則,立即調用該函數。
由於checkme函數中存在相同的錯誤,因此無限遞歸可能會導致瀏覽器死亡。
setTimeout
接受一個函數作為參數,將函數作為參數傳遞的正確方法是將其定義為匿名函數,或者僅提供函數名稱。 如果使用括號(括號),則實際上並未傳遞函數:您正在執行函數並將函數的結果傳遞給setTimeout。
因此,在setTimeout中指定函數時,以及在需要將函數作為參數傳遞的任何其他位置時,不應使用括號。
您不應該在setTimeout函數中使用括號。 您應該只傳遞對該方法的引用。 你正在做的是調用方法並將返回值傳遞給set timeout方法。
如果使用setTimeout(checkme(),4000)
,則傳遞checkme()的返回值; 但是如果你想將它作為一個函數傳遞,你需要通過以下方式進行
setTimeout(function(){checkme()},4000)
要么
st=setTimeout(checkme,4000)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.