SetInterval doesn't seem to like () in the function it calls. What for?

When I do the following, incidentController

gets called after 10

seconds and continues to execute without issue every 10

seconds:

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

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

      

However, this is executed 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); 
}

      

Mistake:

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)

      

It seems to be incidentController

/ is becoming undefined

somehow. Can someone please explain why this is the expected behavior (I am assuming it is anyway)?

I can get around it pretty easily, but I'm just wondering why it behaves this way - makes passing parameter values ​​a little less convenient since I can't do it inside the operator itself setInterval

.

+3


source to share


2 answers


setInterval

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

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

      

you are passing in the result of the call incidentController

, which is undefined

(in JavaScript, if a function doesn't return anything explicitly, then it returns by default undefined

). This is why you are getting the error

Cannot read property 'apply' of undefined

      

It tries to call a function apply

on undefined

.




makes passing parameter values ​​a little less convenient since I cannot do it inside the operator itself setInterval

No sir. You can conveniently pass a parameter to the callback function in itself setInterval

, for example

setInterval(incidentController, 10 * 1000, 123);

      

Now when called incidentController

, every 10 seconds will be passed as the first parameter 123

.

+8


source


Wrong to use setInterval

like

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

      

because it expects the function to be the first parameter (and not an executable function with the result).



If you want to pass a parameter to the callback, you must wrap the function call with an anonymous function, like

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

      

See Pass Parameters in the setInterval Function

+1


source







All Articles