setInterval在它调用的函数中似乎不喜欢()。为什么? [英] setInterval doesn't seem to like () in the function it invokes. Why?

查看:514
本文介绍了setInterval在它调用的函数中似乎不喜欢()。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行以下操作时, incidentController 10 秒后被调用并继续执行,每次都没有问题 10 秒:

When I execute the following, incidentController gets called after 10 seconds and continues to execute with no problems every 10 seconds:

// This works fine in nodejs v0.11.13
setInterval(incidentController, 10 * 1000);

function incidentController () {
 console.log ('executed'); 
}

然而,这会立即执行 并抛出以下内容第二次迭代时出错:

However, this executes immediately and throws the following error on the second iteration:

//This doesn't. The parens which wrap (123) cause the error.

setInterval(incidentController(123), 10 * 1000);

function incidentController (someInt) {
 console.log ('executed: ', someInt); 
}

错误:

timers.js:287
    callback.apply(this, args);
            ^
TypeError: Cannot read property 'apply' of undefined
    at wrapper [as _onTimeout] (timers.js:287:13)
    at Timer.listOnTimeout (timers.js:133:15)

好像是 incidentController is /成为 undefined 以某种方式。有人可以解释为什么这是预期的行为(我认为它是,无论如何)?

It seems like incidentController is/becomes undefined somehow. Can someone explain why this is expected behavior (I assume it is, anyway)?

我可以很容易地解决这个问题,但我只是好奇它为什么会这样做 - 因为我不能将参数值传递得不那么方便在 setInterval 语句本身内进行。

I can work around this pretty easily, but I'm just curious why it behaves this way -- makes passing in parameter values a bit less convenient since I can't do it inside the setInterval statement itself.

推荐答案

setInterval 接受一个函数对象作为第一个参数。但是,当你这样做时

setInterval accepts a function object as the first parameter. But, when you do

setInterval(incidentController(123), 10 * 1000);

您传递的结果是调用 incidentController undefined (在JavaScript中,如果函数没有显式返回任何内容,那么默认情况下, undefined 将被退回)。这就是你收到错误的原因

you are passing the result of invoking incidentController, which is undefined (In JavaScript, if a function doesn't return anything explicitly, then by default, undefined will be returned). That is why you are getting the error

Cannot read property 'apply' of undefined

它试图在<$上调用 apply 函数c $ c> undefined 。

It is trying to invoke the apply function on undefined.


传入参数由于我无法在 setInterval 语句本身内执行此操作,因此值不太方便

makes passing in parameter values a bit less convenient since I can't do it inside the setInterval statement itself

不,先生。您可以方便地将参数传递给 setInterval 本身的回调函数,就像这样

No, sir. You can conveniently pass the parameter to the callback function in setInterval itself, like this

setInterval(incidentController, 10 * 1000, 123);

现在,当调用 incidentController 时,每隔10秒, 123 将作为第一个参数传递给它。

Now, when incidentController is invoked, after every 10 seconds, 123 will be passed as the first parameter to it.

这篇关于setInterval在它调用的函数中似乎不喜欢()。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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