JS宏任务微任务执行顺序
2024年1月25日大约 1 分钟约 441 字
宏任务与微任务的执行顺序
1.宏任务
是指消息队列中的等待被主线程执行的事件,宏任务执行时都会重新创建栈,然后调用宏任务中的函数,栈也会随着变化,但宏任务执行结束时,栈也会随之销毁。
包括 整体代码script,setTimeout,setInterval ,setImmediate,I/O,UI renderingnew ,Promise*
2.微任务
可以把微任务看成是一个需要异步执行的函数,执行时机是在主函数执行结束之后、当前宏任务结束之前
包括 Promises.(then catch finally),process.nextTick, MutationObserver
微任务是基于消息队列、事件循环、UI 主线程还有堆栈而来的
3.执行顺序
宏任务和微任务的区别在于在事件循环机制中,执行的机制不同
每次执行完所有的同步任务后,会在任务队列中取出异步任务,先将所有微任务执行完成后,才会执行宏任务 所以可以得出结论, 微任务会在宏任务之前执行。 我们在工作常用到的宏任务是 setTimeout,而微任务是 Promise.then
注意这里是Promise.then,也就是说 new Promise在实例化的过程中所执行的代码是同步的,而在 then中注册的回调函数才是异步。
例子
setTimeout(function(){
console.log('1')
});
new Promise(function(resolve){
console.log('2');
resolve();
}).then(function(){
console.log('3')
});
console.log('4');
new Promise(function(resolve){
console.log('5');
resolve();
}).then(function(){
console.log('6')
});
setTimeout(function(){
console.log('7')
});
function bar(){
console.log('8')
foo()
}
function foo(){
console.log('9')
}
console.log('10')
bar()最终结果:2,4,5,10,8,9,3,6,1,7
