Why is the behavior of setTimeout(0) and setImmediate() undefined when used in the main module?

后端 未结 1 529
野趣味
野趣味 2020-12-18 05:19

Take the following code taken from the nodejs event loop documentation :

// timeout_vs_immediate.js
setTimeout(() => {
  console.log(\'timeout\');
}, 0);
         


        
相关标签:
1条回答
  • 2020-12-18 06:01

    Essentially, two things happen:

    1. setTimer(0..) gets converted into setTimer(1..)
    2. before the (next) event loop tick begins, node/libuv has to perform a clock_gettime() to get the current time from the system. The time taken for this system call is non deterministic as it depends on the system load at that time. Now, if clock_gettime() took more than 1ms, the setTimer callback will run (#), else event loop continues to next phase (##).

      • In case (#), setTimeout(0,..) callback is run before setImmediate()
      • In case (##), it is otherwise.

    Reference: https://github.com/nodejs/help/issues/392#issuecomment-305969168

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