Execute the setInterval function without delay the first time

后端 未结 14 2350
故里飘歌
故里飘歌 2020-11-22 16:17

It\'s there a way to configure the setInterval method of javascript to execute the method immediately and then executes with the timer

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 16:45

    There's a convenient npm package called firstInterval (full disclosure, it's mine).

    Many of the examples here don't include parameter handling, and changing default behaviors of setInterval in any large project is evil. From the docs:

    This pattern

    setInterval(callback, 1000, p1, p2);
    callback(p1, p2);
    

    is identical to

    firstInterval(callback, 1000, p1, p2);
    

    If you're old school in the browser and don't want the dependency, it's an easy cut-and-paste from the code.

提交回复
热议问题