setInterval doesn't seem to like () in the function it invokes. Why?

China☆狼群 提交于 2019-11-28 01:30:29

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

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

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

It is trying to invoke the apply function on undefined.


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

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

setInterval(incidentController, 10 * 1000, 123);

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

AmmarCSE

It is incorrect to use setInterval like

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

because it expects a function as the first parameter(not an executed function with a result).

If you wish to pass a parameter to the call back, you should wrap the function call with an anonymous function like

setInterval(function(){incidentController(123)}, 10 * 1000);

See Pass parameters in setInterval function

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