console.log('start');
setTimeout(() => {
console.log('children2');
Promise.resolve().then(() => {
console.log('children3');
})
}, 0);
new Promise(function (resolve, reject) {
console.log('children4');
setTimeout(function () {
console.log('children5');
resolve('children6')
}, 0)
}).then((res) => {
console.log('children7');
setTimeout(() => {
console.log(res);
}, 0)
})
//輸出
//start 4 2 3 5 7 6
宏任務
包括:包含執行整體的js代碼,事件回調,XHR回調,定時器(setTimeout/setInterval/setImmediate),IO操作,UI render
微任務
包括:更新應用程序狀態的任務,包括promise回調,MutationObserver,process.nextTick,Object.observe
image.png
事件循環的步驟
1.執行宏任務隊列中的一個任務
2.執行微任務隊列中的所有任務
3.UI render
setTimeout(function() {console.log('timer1')}, 0)
requestAnimationFrame(function(){
console.log('requestAnimationFrame')
})
setTimeout(function() {console.log('timer2')}, 0)
new Promise(function executor(resolve) {
console.log('promise 1')
resolve()
console.log('promise 2')
}).then(function() {
console.log('promise then')
})
console.log('end')
//輸出1 : promise1,promise2,end,promise then,requestAnimationFrame,timer1,timer2
//輸出2 : promise1,promise2,end,promise then,timer1,timer2,requestAnimationFrame