Macro queue and micro queue, event-loop event loop

执行顺序:
	javaScript的单线程机制,会执行完所有同步任务,再去执行队列中的任务
	相同类型的任务,从上往下执行
	不同类型:微队列任务优先级高于宏队列任务
		(1)会先执行完所有微队列任务,再去执行宏队列任务
		(2)每次准备取出执行下一个宏队列任务之前,都要将微队列中的任务全部取出来执行

宏队列任务:dom回调、ajax回调、定时器回调、dom渲染等,是由浏览器规定的
微队列任务:Promise回调、mutationObserver回调、await 后面的函数是同步的,下方的剩余代码是微任务、process.nextTick等,是由es6规定的
	其中:
		微队列中的微队列会被放进已存在的微队列栈的最后,而非在其父微队列任务其后执行,具体看第二个示例代码
		Promise中的方法是同步调用的,.then的回调才是异步

event-loop事件循环:
	同步代码放到call stack中执行,然后执行微任务,再进行dom渲染,宏任务会等待到调用时移动到call queue中,若call stack空掉了,event-loop开始工作,轮询查找call queue,若有则移动到call stack,然后继续轮询

Insert picture description hereInsert picture description here

//执行结果:3-4-1-2-h1-3-h2
setTimeout(() => {
    
    
  console.log('h1');
  Promise.resolve(3).then((res) => {
    
    
    console.log(res);
  })
}, 0)
setTimeout(() => {
    
    
  console.log('h2');
}, 0)
new Promise(() => {
    
    
  console.log(3);
})
Promise.resolve(1).then((res) => {
    
    
  
  console.log(res);
})
Promise.resolve(2).then((res) => {
    
    
  console.log(res);
})

console.log(4);

Execution result: 1-7-2-3-8-4-6-5-0
first execute synchronization task 1, and then put the method parameters in the .then into the micro queue
-> then execute synchronization task 7, set 7 Then put the parameters of the .then method into the micro-queue
-> the micro-queue after the execution of 1 -> output the synchronization result 2, 3-> put the .then method parameters into the micro-queue
-> execute the micro-task after 7, Output 8
-> put 4 callbacks into the micro queue, because 5 depends on the result of 4, so execute it first, put the callback parameters of 6 into the micro queue
-> then put 5 into the micro queue -> finally execute the macro queue 0
Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43294560/article/details/115280317