Skip to content Skip to sidebar Skip to footer

What's The Differenct Between Passing A Function And The Function Call Itself In Javascript?

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://loca

Solution 1:

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

Solution 2:

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.

Solution 3:

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

Post a Comment for "What's The Differenct Between Passing A Function And The Function Call Itself In Javascript?"