开发者

What's the differenct between passing a function and the function call itself in javascript?

开发者 https://www.devze.com 2023-01-01 10:13 出处:网络
In the application I\'m building I\'m polling for a status update and I have noticed that if the call is made as follows the timeout fires continuously:

In the application I'm building I'm polling for a status update and I have noticed that if the call is made as follows the timeout fires continuously:

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

While if use a function instead the timeout fires every 1000 ms:

 setTimeout(function() {$.get("http://localhost:8080/status", fun开发者_如何转开发ction(data) { UpdateStatus(data);})}, 1000);

Why?


In the first example, you're calling $.get and then passing its return value into setTimeout. In the second example, you're not calling the function at all; you're giving setTimeout a function that it will call later, which will then call $.get for you.

This is easier to see with a simpler test case:

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);

Note that the first one has parentheses (()), the second one doesn't.

When you want to pass parameters to the function, you have to do it indirectly by defining another function:

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);


In the first example the first parameter to setTimeout is getting assigned the result of $.get (wrong), whereas in the second example it is actually receiving a parameter of type function, which will be correctly evaluated as a set of javascript statements every x milliseconds.


You shouldn't be passing the result of a function call to setTimeout - there's no sense in doing that. First argument should be the function itself, not the call.

Why it fires continuously - a strange side-effect, who knows :)

0

精彩评论

暂无评论...
验证码 换一张
取 消