What is the difference between passing a function and a function invoking itself in javascript?

In the application that I am creating, I check the update status, and I noticed that if the call is executed as follows, the timeout works continuously:

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

If, when using the function, the timeout is triggered every 1000 ms:

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

Why?

+3
source share
3 answers

In the first example, you call $.getand then pass its return value to setTimeout. In the second example, you do not call this function at all; you provide a setTimeoutfunction that will be called later, after which you will call $.getfor you.

This is easier to see in a simpler 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);

, (()), - .

, , :

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

setTimeout $.get (), , javascript x .

+3

setTimeout - . , .

- , :)

0

Source: https://habr.com/ru/post/1747859/


All Articles