宏任务:
setTimeout
setInterval
setImmediate (Node独有)
requestAnimationFrame (浏览器独有)
I/O
UI rendering (浏览器独有)
微队列:
process.nextTick (Node独有)
Promise
Object.observe
MutationObserver
1.执行全局Script同步代码
2.全局Script代码执行完毕后,调用栈Stack会清空;从微队列microtask queue中取出位于队首的回调任务,放入调用栈
继续取出位于队首的任务,放入调用栈Stack中执行,以此类推,直到直到把microtask queue中的所有任务都执行完毕。
microtask queue中的所有任务都执行完毕,此时microtask queue为空队列,调用栈Stack也为空;
3.取出宏队列macrotask queue中位于队首的任务,放入Stack中执行;
执行完毕后,调用栈Stack为空;
4.重复第3-7个步骤;
例:
console.log(1);
setTimeout(() => {
console.log(2);
Promise.resolve().then(() => {
console.log(3)
});
});
new Promise((resolve, reject) => {
console.log(4)
resolve(5)
}).then((data) => {
console.log(data);
Promise.resolve().then(() => {
console.log(6)
}).then(() => {
console.log(7)
setTimeout(() => {
console.log(8)
}, 0);
});
})
setTimeout(() => {
console.log(9);
})
console.log(10);
1
4
10
5
6
7
2
3
9
8