2010-05-31 46 views
3

在應用我建我的狀態更新輪詢和我已經注意到,如果呼叫被製成連續地跟隨超時火災:在javascript中傳遞函數和函數調用本身有什麼不同?

setTimeout($.get("http://localhost:8080/status", function(data) { UpdateStatus(data);}), 1000); 

而如果使用一個函數,而不是超時火災每1000毫秒:

setTimeout(function() {$.get("http://localhost:8080/status", function(data) { UpdateStatus(data);})}, 1000); 

爲什麼?

+0

的可能重複[?爲什麼是應該由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

回答

3

在第一個示例中,您是,致電$.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); 
+1

我是新來的Javascript,但我應該'已經看到了,謝謝! – mbesso 2010-05-31 14:55:05

0

您不應該將函數調用的結果傳遞給setTimeout--這樣做沒有意義。 第一個參數應該是函數本身,而不是調用。

爲什麼它不斷地激發 - 一個奇怪的副作用,誰知道:)

3

在第一個例子setTimeout的第一個參數是在第二個例子中得到分配結果$.get(錯誤),而它實際上正在接收一個函數類型的參數,它將每x毫秒正確評估爲一組JavaScript語句。

相關問題