node.js: setInterval() skipping calls

前端 未结 4 612
一向
一向 2021-02-04 11:37

For an upcoming project with node.js I need to perform various housekeeping tasks at periodic times. Specifically some tasks every millisecond, others every 20 ms (50 times per

4条回答
  •  时光取名叫无心
    2021-02-04 12:19

    Look at this doc: http://nodejs.org/api/timers.html#timers_settimeout_callback_delay_arg

    It is important to note that your callback will probably not be called in exactly delay milliseconds - Node.js makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in. The callback will be called as close as possible to the time specified.

    This happens because application code blocks the event loop. All timers and I/O events can be handled only on the nextTick.

    You can see this behaviour with this code:

    setInterval(function() {
        console.log(Date.now());
        for (var i = 0; i < 100000000; i++) {
        }
    }, 1);
    

    Try to change iterations count and see results.

    Ideally, the timer will be triggered exactly if the applications tick will last less than one ms. But this is not practicable in a real application.

提交回复
热议问题