一、宏任务和微任务
宏任务(macrotask) | 微任务(microtask) | |
---|---|---|
由谁发起 | 宿主(Node、浏览器) | JS引擎 |
具体事件 | 1. script (可以理解为外层同步代码) 2. setTimeout/setInterval 3. UI rendering/UI事件 4. postMessage,MessageChannel 5. setImmediate,I/O(Node.js) | 1. Promise 2. MutaionObserver 3. Object.observe(已废弃;Proxy 对象替代) 4. process.nextTick(Node.js) 5. async/await |
谁先运行 | 后运行 | 先运行 |
会触发新一轮Tick吗 | 会 | 不会 |
二、例子
setTimeout(() => {
//执行后 回调一个宏事件
console.log('内层宏事件3')
}, 0)
console.log('外层宏事件1');
new Promise((resolve) => {
console.log('外层宏事件2');
resolve()
}).then(() => {
console.log('微事件1');
}).then(()=>{
console.log('微事件2')
})
执行结果如下:
外层宏事件1
外层宏事件2
微事件1
微事件2
内层宏事件3
四、总结
微任务执行时机比宏任务早
宏任务和微任务的执行过程如下(从菱形开始):
js异步有一个机制,就是遇到宏任务,先执行宏任务,将宏任务放入eventqueue,然后在执行微任务,将微任务放入eventqueue,但是这两个queue不是一个queue
。当你往外拿的时候先从微任务里拿这个回掉函数,然后再从宏任务的queue上拿宏任务的回掉函数
。
参考:https://zhuanlan.zhihu.com/p/78113300
https://www.jianshu.com/p/d08e235e17af