在我正在构建的应用程序中,我正在轮询状态更新,我注意到如果按以下方式进行调用,超时将持续触发:
setTimeout($.get("http://localhost:8080/status", function(data) { UpdateStatus(data);}), 1000);
如果使用函数代替,则超时每 1000 毫秒触发一次:
setTimeout(function() {$.get("http://localhost:8080/status", function(data) { UpdateStatus(data);})}, 1000);
为什么?
最佳答案
在第一个示例中,您调用 $.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);
关于javascript - 在javascript中传递函数和函数调用自身有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2944207/