浅析Event Loop - 图1

    事件循环是由一系列阶段构成的
    setTimeout()会被放在timers阶段
    setImmediate()会被放在check阶段
    process.nextTick()会在当前阶段结束后紧跟着执行

    来判断如下代码的用node.js执行后输出顺序

    1. setTimeout(()=>console.log('setTimeout'),0)
    2. setImmediate(()=>console.log('setImmediate'))
    3. /*
    4. output:
    5. setTimeout
    6. setImmediate
    7. */
    8. //或
    9. /*output
    10. setImmediate
    11. setTimeout
    12. */

    可以发现执行两个计时器的顺序是非确定性的。
    因为不在 I/O 周期(即主模块)内的运行的脚本,它受进程性能的约束。

    如果把这两个函数放入I/O循环内调用,setImmediate总是会先被调用

    1. const fs = require('fs');
    2. fs.readFile(__filename, () => {
    3. setTimeout(() => {
    4. console.log('setTimeout');
    5. }, 0);
    6. setImmediate(() => {
    7. console.log('setImmediate');
    8. });
    9. });
    10. /*output
    11. setImmediate
    12. setTimeout
    13. */

    把这两个函数放在setTimeoutsetImmediate里调用,setImmediate也总是会被先调用

    1. setImmediate(()=>{
    2. setTimeout(()=>console.log('setTimeout'),0)
    3. setImmediate(()=>console.log('setImmediate'))
    4. })
    5. /*output
    6. setImmediate
    7. setTimeout
    8. */
    1. setTimeout(()=>{
    2. setTimeout(()=>console.log('setTimeout'),0)
    3. setImmediate(()=>console.log('setImmediate'))
    4. },0)
    5. /*output
    6. setImmediate
    7. setTimeout
    8. */

    关于process.nextTick()的执行顺序

    1. setTimeout(()=>{
    2. setTimeout(()=>console.log('setTimeout'),0)
    3. setImmediate(()=>console.log('setImmediate'))
    4. process.nextTick(()=>console.log('nextTick'))
    5. },0)
    6. /*output
    7. nextTick
    8. setImmediate
    9. setTimeout
    10. */
    1. setTimeout(() => {
    2. setTimeout(() => console.log("setTimeout"), 0);
    3. setImmediate(() => {
    4. process.nextTick(() => console.log("nextTick"));
    5. console.log("setImmediate");
    6. });
    7. }, 0);
    8. /*output
    9. setImmediate
    10. nextTick
    11. setTimeout
    12. */
    1. setTimeout(() => {
    2. setTimeout(() => {
    3. process.nextTick(() => console.log("nextTick"));
    4. console.log("setTimeout");
    5. }, 0);
    6. setImmediate(() => console.log("setImmediate"));
    7. }, 0);
    8. /*output
    9. setImmediate
    10. setTimeout
    11. nextTick
    12. */