I have the following code:
var foo=5;
var los= function (){
alert(foo);};
setInterval(los, 1000);
which works correctly.
If I change it to :
var los= function (){
alert(foo);};
setInterval(los(), 1000);
it only executes once with no errors in console.
Can someone explain me why this happens when I include the parentesis after los
in the setInterval
function?
Keep in mind that in JavaScript a function is an object, passed around like any other variable. So this is a reference to the function:
This, on the other hand, executes the function and evaluates to its result:
So when you do this:
You're not setting the interval to the function, but to the result of the function. So, for example, if the function returns
true
then you're essentially writing this:The function executed once, then the interval is repeated for its result. What you want is to use the function reference itself in the interval:
That way
setInterval
will execute the function each interval, instead of executing its result (which doesn't do anything).Because you're executing
los()
and then the result of that (single) execution is passed into thesetInterval
function.setInterval
requires a function passed in, notundefined
, which is whatlos
returns. However, it doesn't complain - it just doesn't do anything.The
()
you've got in the second one means to call the function before passing the result tosetInterval
. The parentheses are the operator that explicitly request that a function be called; that's why you put the parentheses around the arguments tosetInterval
, after all.The name of a function, by itself, is a valid expression in JavaScript. The value of such an expression is a reference to the function. That's the value that you want when you're setting up an interval timer — you want to tell the system what function to call when the timer expires, so you pass a reference to it.