This question already has an answer here:
-
what is the difference between calling function in JavaScript with or without parentheses ()
3 answers
I have a script that counts up the number in a box (actually, in this exercise -> http://jqexercise.droppages.com/#page_0022_ ) each 1 second like this.
var target = $("#target input");
var countUp = function(){
target.val(parseInt(target.val())+1);
setTimeout(countUp,1000); // this line
};
countUp();
My questions is, when i change countUp
to countUp()
at the line I marked with // this line
, it instantly counts up to 15616. What is the difference between those?
countUp
references the function as an object. In JavaScript everything is an object, including functions, and can be passed around. countUp()
calls the function countUp
and returns its value.
Adding the ()
to the function invokes it instantly, while just using the function name is actually passing it as a parameter.
countUp()
is a recursive invocation of the function. Each call to the function invokes it again (immediately), and the return value (which is undefined
) is passed to setTimeout.
This would be an infinite loop, except I believe the exception from setTimeout
receiving a non function is interrupting it after 1 second, leading to a stop at 15616.
In a nutshell, the setTimeout(countUp, 1000); sets the time to execute the countup function in milliseconds seconds every nth second. Which in this case would be 1 second. countup is just being passed as a parameter into the setTimeout function here.