SetInterval函数调用 [英] SetInterval function calls

查看:187
本文介绍了SetInterval函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里陷入困惑。请仔细阅读下面的代码,

 < script> 

setInterval(function1,3000);

setInterval(function2(),3000);

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


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

< / script>

正如你所看到的,我有两个 setInterval 函数调用函数如 function1 和另一个 function2()。第一个输出是完美的,每3秒调用一次,3秒后首先调用。但是第二个被调用没有延迟,即 function2



我想 可能在那里做事,但我不确定我在那里失踪。我只想知道那里发生了什么。在第二个 setInterval

解决方案

c>您正在执行它并将该函数返回的值插入 setInterval



例如,

  setInterval(a(),5000); 
函数a(){
返回函数(){
console.log(Executed!);
};
};

a()执行并返回函数 setInterval 中。你应该看到控制台每5秒钟写入 Executed



这就像数学:

(2)

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ )= g(x)+ 2 = 4
将g(2)替换为任何它返回的
(在这种情况下用函数替换一个())

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

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.

解决方案

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/

这篇关于SetInterval函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆