lstoryc / lstoryc.github.io

My Blog
2 stars 0 forks source link

Q3. 事件循环 Event Loop #6

Open lstoryc opened 4 years ago

lstoryc commented 4 years ago

什么是Event Loop 事件循环

有能力的同学请看视频讲解 Philip Roberts 大神: https://www.youtube.com/watch?v=8aGhZQkoFbQ Jake Archibald 大神: https://www.youtube.com/watch?v=cCOL7MC4Pl0 https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/

lstoryc commented 4 years ago

宏任务和微任务执行顺序问题讲解

function test() {
  console.log("start");
  setTimeout(() => {
    console.log("children2");
    Promise.resolve().then(() => {
      console.log("children2-1");
    });
  }, 0);
  setTimeout(() => {
    console.log("children3");
    Promise.resolve().then(() => {
      console.log("children3-1");
    });
  }, 0);
  Promise.resolve().then(() => {
    console.log("children1");
  });
  console.log("end");
}

test();

在node11以下版本的执行结果(先执行所有的宏任务,再执行微任务)

// start
// end
// children1
// children2
// children3
// children2-1
// children3-1

在node11+及浏览器的执行结果(顺序执行宏任务和微任务,一个宏任务 => 微任务+ => 下一个宏任务 => 下一个微任务+ ... )

// start
// end
// children1
// children2
// children2-1
// children3
// children3-1

注意: 宏任务内若嵌套同源宏任务,仍会放进一个队列,但是执行将会放在下一次事件循环;(举个栗子,timeoutTwo中包含一个timeoutThree,timeoutThree仍会放进setTimeout队列,但并不会与timeoutOne、timeoutTwo一起执行完毕,而是等到清空微任务队列的下一次循环时执行);

lstoryc commented 4 years ago

浏览器下宏任务微任务和页面渲染之间过程讲解:

lstoryc commented 4 years ago

async await

https://jakearchibald.com/2017/await-vs-return-vs-return-await/