Search code examples
javascriptfunctionsetintervalparentheses

Javascript function in setInterval


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?


Solution

  • 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:

    los
    

    This, on the other hand, executes the function and evaluates to its result:

    los()
    

    So when you do this:

    setInterval(los(), 1000)
    

    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:

    setInterval(true, 1000)
    

    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:

    setInterval(los, 1000)
    

    That way setInterval will execute the function each interval, instead of executing its result (which doesn't do anything).