Reference T questions:
Draw each Queue, sequentially thrown in are performed by the step of outputting
Browser:
- Macrotask (macroTask): script code, setTimeout, setInterval, I / O, UI render;
- Micro-task (microTask): Promise, Object.observe, MutationObserver.
(Promise itself is synchronized, then is micro)
while (true) {
宏任务队列.shift()
微任务队列全部任务()
}
Node:
- micro
- timer
- I / O
- check
- use Close
(Other, less commonly ignored in this article)
- Before the cycle
before entering the first cycle, we will carry out the following operations:
- Synchronization task
- An asynchronous request
- Time to plan a timer in force
- Execution process.nextTick ()
- Start the cycle:
while (true) {
loop.forEach((阶段) => {
阶段全部任务()
nextTick全部任务()
microTask全部任务()
})
loop = loop.next
}
Small Exercise:
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);
});
Reference
https://segmentfault.com/a/1190000013660033?utm_source=channel-hottest
Reproduced in: https: //www.jianshu.com/p/1c3b894e6c2d