Vinay
Vinay

Reputation: 6881

SetInterval function calls

I am getting into sort of confusion here. Please go through the below code,

<script>

setInterval(function1,3000);

setInterval(function2(),3000);

function function1() {
    console.log("Function1 called....");
}

function function2() {
    console.log("Function2 called....");
}

</script>

As you can see I have two setInterval functions one calls function like function1 and another function2(). The output of first is perfect that gets called every 3sec and first call after 3sec. But second one gets called without the delay i.e function2.

I guess that () might be doing things there but I'm not sure about what I'm missing there. I just want to know what is happening there.

Upvotes: 0

Views: 514

Answers (3)

Eugen Rieck
Eugen Rieck

Reputation: 65264

setInterval(function1,3000); instructs the JS engine to execute the function function1 every 3 seconds.

setInterval(function2(),3000); instructs the JS engine to run function2 once, then run the return value every 3 seconds. This return value is empty.

For a bit of fun try

function function2() {
    console.log("Function2 called....");
    return "function3();"
}

function function3() {
    console.log("Function3 called....");
}

setInterval(function2(),3000);

Edit

In reponse to @harsha's comment: What do I mean by "run the return value"

setInterval(function2(),3000); will trigger the following workflow:

  • Initiate executing function2() (execute it, because it the brackets are given).
  • function2 runs to completion, then returns.
    • In your OQ, there is no return value from the function so it is null
    • The return value of my function2 is the string "function3();"
  • This return value is now inserted into the setInterval() call
    • The OQ version results in setInterval(null, 3000);, which does nothing every 3 seconds
    • My version results in setInterval("function3();", 3000), which calls eval("function3();"); every 3 seconds, which in turn runs function3 every 3 seconds.

Upvotes: 3

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

In the second setInterval you are executing it right away and plugging the value returned by that function into setInterval.

For example,

setInterval(a(), 5000);
function a(){
    return function(){
        console.log("Executed!");
    };
};

a() executed and returning the function into setInterval. You should see the console is writing Executed every 5 seconds.

This is just like math:

f(x) = x + 1
g(x) = 2

f(g(2)) = g(x) + 2 = 4
You replace g(2) with whatever it returns
(you replace a() with the function in this case)

http://jsfiddle.net/DerekL/39wNn/

Upvotes: 1

everconfusedGuy
everconfusedGuy

Reputation: 2797

The () makes the function get executed immediately in the second case. In the first case, just the pointer to function which gets executed later as the call back function.

Upvotes: 1

Related Questions