Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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://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", function(data) { UpdateStatus(data);})}, 1000);

Why?

like image 900
mbesso Avatar asked May 02 '26 16:05

mbesso


2 Answers

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);
like image 146
T.J. Crowder Avatar answered May 05 '26 08:05

T.J. Crowder


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.

like image 29
karim79 Avatar answered May 05 '26 08:05

karim79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!