【发布时间】:2015-05-24 03:09:08
【问题描述】:
当我执行以下操作时,incidentController 会在 10 秒后被调用,并在每 10 秒后继续执行,没有问题:
// This works fine in nodejs v0.11.13
setInterval(incidentController, 10 * 1000);
function incidentController () {
console.log ('executed');
}
但是,这会立即执行,并在第二次迭代时抛出以下错误:
//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 以某种方式成为/变成了undefined。有人可以解释为什么这是预期的行为(无论如何我认为它是)?
我可以很容易地解决这个问题,但我只是很好奇它为什么会这样——因为我不能在 setInterval 语句本身中这样做,所以传递参数值不太方便。
【问题讨论】:
-
因为你正在执行函数! :) 它不知道您要为其分配引用。
标签: javascript node.js setinterval