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?
In the first example, you’re calling
$.getand then passing its return value intosetTimeout. In the second example, you’re not calling the function at all; you’re givingsetTimeouta function that it will call later, which will then call$.getfor you.This is easier to see with a simpler test case:
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: