宏任务:setTimeout,setInterval,ajax,DOM事件
微任务:Promise,async/await
微任务执行时机比宏任务早
console.log(100)
//宏任务
setTimeout(()=>{
console.log(200)
})
//微任务
Promise.resolve.then(()=>{
console.log(300)
})
console.log(400)
//打印顺序:100,400,300,200
为什么微任务比宏任务执行的早
- 宏任务:DOM渲染后触发,如setTimeOut
- 微任务:DOM渲染前触发,如Promise
宏任务和微任务的根本区别
- 宏任务是浏览器规定的;
- 微任务是es6语法规定的;
- 微任务等待时机放在micro task queue中,首先执行同步代码,当代码执行完成,call stack清空之后,执行当前的微任务,再尝试DOM渲染,最后触发event loop机制;
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。