在第一个示例中,您是,致电$.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