事件循环 浏览器vsNode

笔试题参考:
画出各个queue,执行时依次丢进去,按步骤执行、输出

浏览器:

  • 宏任务(macroTask):script 中代码、setTimeout、setInterval、I/O、UI render;
  • 微任务(microTask): Promise、Object.observe、MutationObserver。

(promise本身是同步的,then才是micro)

while (true) {
  宏任务队列.shift()
  微任务队列全部任务()
}

Node:

process.nextTick、microTask

  • timer: setTimeout、setInterval
  • I/O: fr.readFileSync
  • check: setImmediate
  • close: 不常用
    (其他不常用的本文忽略)
  1. 循环之前
    在进入第一次循环之前,会先进行如下操作:
  • 同步任务
  • 发出异步请求
  • 规划定时器生效的时间
  • 执行process.nextTick()
  1. 开始循环:
while (true) {
  loop.forEach((阶段) => {
    阶段全部任务()
    nextTick全部任务()
    microTask全部任务()
  })
  loop = loop.next
}

小练习:

function sleep(time) {
  let startTime = new Date();
  while (new Date() - startTime < time) {}
  console.log("1s over");
}
setTimeout(() => {
  console.log("setTimeout - 1");
  setTimeout(() => {
    console.log("setTimeout - 1 - 1");
    sleep(1000);
  });
  new Promise(resolve => resolve()).then(() => {
    console.log("setTimeout - 1 - then");
    new Promise(resolve => resolve()).then(() => {
      console.log("setTimeout - 1 - then - then");
    });
  });
  sleep(1000);
});

setTimeout(() => {
  console.log("setTimeout - 2");
  setTimeout(() => {
    console.log("setTimeout - 2 - 1");
    sleep(1000);
  });
  new Promise(resolve => resolve()).then(() => {
    console.log("setTimeout - 2 - then");
    new Promise(resolve => resolve()).then(() => {
      console.log("setTimeout - 2 - then - then");
    });
  });
  sleep(1000);
});

参考
https://segmentfault.com/a/1190000013660033?utm_source=channel-hottest

你可能感兴趣的:(事件循环 浏览器vsNode)