2010-05-31 24 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语句。

相关问题