SetInterval function calls

a 夏天 提交于 2019-12-25 11:17:13

问题


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.


回答1:


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/




回答2:


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.



回答3:


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.



来源:https://stackoverflow.com/questions/16850138/setinterval-function-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!