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

后端 未结 2 1676
盖世英雄少女心
盖世英雄少女心 2020-12-06 22:34

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

相关标签:
2条回答
  • 2020-12-06 23:17

    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.

    0 讨论(0)
  • 2020-12-06 23:23

    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

    0 讨论(0)
提交回复
热议问题