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
事件循环的步骤
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