使用需要参数的非匿名函数的setInterval必须在匿名函数内。为什么? [英] setInterval using a non anonymous function requiring parameters has to be inside an anonymous function. Why?

查看:745
本文介绍了使用需要参数的非匿名函数的setInterval必须在匿名函数内。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经在jquery / javascript中查看了有关setInterval的几个帖子和其他地方关于答案的烦人的事情,我不知道为什么解决方案有效。

Ok I have reviewed several postings here and elsewhere regarding setInterval in jquery/javascript the annoying thing about the answers is that I am not learning why the solutions work.

请考虑:

使用匿名函数我们可以设置警报以重复输出兔子:

Using an anonymous function we can set an alert to repeatedly output "bunnies":

setInterval(function(){
  alert("bunnies")
},3000);

但如果我们想使用非匿名函数,我们必须编码

But if we want to use a non anonymous function we have to code


setInterval(hop,3000);

setInterval(hop,3000);

其中funct:

function hop(){
    alert("bunnies");
}

如果我们尝试编码:

setInterval(hop(),3000);

跳跃只执行一次。我不明白为什么会这样。我已经阅读了各种SO,这意味着我们需要传递对setInterval的引用。这是否意味着第一个形式setInterval(hop,3000);通过引用传递。如果是这样可以解释?

hop is executed but once only. I do not understand why this is. I have read various SO's on this which imply that we need to be passing a reference to setInterval. Does this imply that the first form setInterval(hop,3000); passes by reference. If so could this be explained?

因此我们遇到了问题。显然,希望能够将参数传递给函数跳像......

Therefore we have an issue. In that obviously it would be desireable to be able to pass a parameter to function hop like .....

setInterval(hop("bunnies"),3000);

其中功能:

function hop(msg){
    alert(msg);
}

这会导致调用hop并输出bunnies但是该函数只调用一次。

This does cause hop to be invoked and "bunnies" to be output but again the function is invoked once only.

因此,我可以计算出将参数传递给由setInterval控制的函数的唯一方法是将其合并到一个函数中。匿名函数:

So as far as I can work out the only way to pass a parameter to a function being controlled by setInterval is to incorporate it inside an anonymous function:

setInterval(function(){
 hop("bunnies")
},3000);

这会传递参数并重复执行跳跃,每三秒钟警告我们一次兔子(非常重要的是警惕兔子)。

this passes the parameter and repeats the execution of hop alerting us to bunnies every 3 seconds (very important to be alert to bunnies).

因此问题:


  1. 这是唯一的允许你传入参数的语法。

  2. 为什么setInterval(hop(bunnies),3000);不行。


推荐答案

setInterval 期望函数作为第一个参数。当你尝试:

setInterval expects a function as the first parameter. When you attempt:

setInterval(function() {...}, 100);

setInterval(funcName, 100);

您正确传递函数。

然而,当您尝试 setInterval(funcName(),100); 时,您实际上是调用该函数并将其返回值传递给 setInterval 哪个不正确。

Whereas, when you attempt setInterval(funcName(), 100);, you are actually calling the function and passing its return value to setInterval which is incorrect.

这篇关于使用需要参数的非匿名函数的setInterval必须在匿名函数内。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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