在第一個示例中,您是,致電$.get
,然後將其返回值傳遞到setTimeout
。在第二個例子中,你根本不調用函數;你給setTimeout
函數它將稍後調用,然後將爲您調用$.get
。
這種情況很容易看到一個簡單的測試案例:
function test() {
alert("Hi there!");
}
// WRONG, *calls* `test` immediately, passes its return value to `setTimeout`:
setTimeout(test(), 1000);
// Right, passes a reference to `test` to `setTimeout`
setTimeout(test, 1000);
注意,第一個具有括號(()
),第二個沒有。
當你想參數傳遞給函數,你必須定義另一個函數來做到這一點間接:
function test(msg) {
alert(msg);
}
// WRONG, *calls* `test` immediately, passes its return value to `setTimeout`:
setTimeout(test("Hi there!"), 1000);
// Right, passes a reference to a function (that will call `test` when called) to `setTimeout`
setTimeout(function() { test("Hi there!"); }, 1000);
的可能重複[?爲什麼是應該由setTimeout的安排我的函數調用立即執行] (http://stackoverflow.com/questions/2037203/why-is-my-function-call-that-should-be-scheduled-by-settimeout-executed-immediat) – outis 2012-01-20 10:31:36