![](/img/trans.png)
[英]When does a javascript settimeout or setinterval function stop?
[英]Calling a function when using setTimeout() and setInterval() in JavaScript
如果我使用不帶括號的setTimeout()和setInterval()調用命名函數,它將按預期工作。 當我用括號調用相同的函數時,它要么立即執行它,要么給出錯誤。
我正在尋找比我在網上發現的更深刻的理解。 你們能告訴我為什么這是真的嗎?
var func = function(){
console.log("Bowties are cool.");
}
setTimeout(func(), 1500);
// Prints "Bowties are cool." immediately
setInterval(func(), 1500);
// Throws an error
setInterval(func, 1500);
// Works as expected
setTimeout(console.log("Bowties are cool."),1500);
// This method has the same result as "setTimeout(func(), 1500)".
您必須將函數引用傳遞給setTimeout()
和setInterval()
。 這意味着您傳遞的函數名稱后不帶()
,或者傳遞匿名函數。
當包括()
函數名后,如func()
你會立即執行該功能,然后通過返回結果setInterval()
或setTimeout()
除非函數本身返回另一個函數引用,否則它將永遠不會做您想要的事情。 對於Javascript程序員來說,這是一個非常常見的錯誤(我自己在學習語言時犯了同樣的錯誤)。
因此,正確的代碼是:
setTimeout(func, 1500);
setInterval(func, 1500);
如果您知道其他使用指針的語言,則可以在函數名稱后加上()
來表示該函數的名稱,就像該函數的指針一樣,這就是Javascript中的函數引用,也就是您在傳遞給函數時的含義希望它能夠稍后而不是立即執行某些功能。
當您錯誤地執行此操作時:
setTimeout(func(), 1500);
setInterval(func(), 1500);
它會立即執行func()
,然后將返回結果傳遞給setTimeout()
和setInterval()
。 由於func()
不返回任何內容,因此您實際上是在這樣做:
func();
setTimeout(undefined, 1500);
您觀察到的是正在發生的事情,而不是您想要的。
此外,如果要執行特定的函數調用,例如console.log("Bowties are cool.")
,則可以將其包裝在另一個函數中,如下所示:
setTimeout(function() {
console.log("Bowties are cool.")
}, 1500);
因此,您再次向setTimeout()
傳遞了一個函數引用,該函數引用可以稍后執行,而不是立即執行此操作。
setTimeout和setInterval希望將函數引用傳遞給它們。 您不應在setTimeout和setInterval調用內調用該函數。
不正確( 請勿這樣做 ):
setTimeout(func(), 1500);
setInterval(func(), 1500);
setTimeout(console.log("Bowties are cool."), 1500);
setInterval(console.log("Bowties are cool."), 1500);
正確:
setTimeout(func, 1500);
setInterval(func, 1500);
setTimeout(function() {
console.log("Bowties are cool.");
}, 1500);
setInterval(function() {
console.log("Bowties are cool.");
}, 1500);
請注意我如何將console.log包裹在一個匿名函數中,以便與setInterval和setTimeout一起使用。 我無法將console.log
傳遞給setInterval和setTimeout函數,因為它需要參數"Bowties are cool."
。 將其包裝在匿名函數中可以解決此問題。
在定義的函數后添加括號時,實際上是在調用或調用該函數。
但是,當您將一個函數作為參數傳遞給另一個函數時,您不想調用該函數,而只是想將該函數的引用作為參數傳遞,(而您傳入的函數將可用於在需要時調用)。
有關一般回調函數的更多信息,請參見此處 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.