Event Loop 与微任务/宏任务
约 369 字大约 1 分钟
布欧-Lewyon
2026-05-16
首页 › JavaScript › 异步编程 › Event Loop 与微任务/宏任务
单线程与事件循环
JavaScript 是单线程语言。Event Loop 是 JS 管理异步操作的机制。
执行顺序
console.log('1'); // 1. 同步
setTimeout(() => {
console.log('2'); // 4. 宏任务
}, 0);
Promise.resolve().then(() => {
console.log('3'); // 3. 微任务
});
console.log('4'); // 2. 同步
// 输出顺序:1 → 4 → 3 → 2完整规则
- 执行同步代码(调用栈)
- 清空微任务队列(Promise.then / catch / finally / MutationObserver)
- 取一个宏任务执行(setTimeout / setInterval / I/O / UI 渲染)
- 回到步骤 2
常见面试题
console.log(1);
setTimeout(() => console.log(2), 0);
Promise.resolve().then(() => {
console.log(3);
setTimeout(() => console.log(4), 0);
Promise.resolve().then(() => console.log(5));
});
console.log(6);
// 输出:1 → 6 → 3 → 5 → 2 → 4
// 过程:
// 1. 同步:1, 6
// 2. 微任务:3
// 3. 微任务中注册的微任务:5(清空本轮微任务队列)
// 4. 宏任务:2
// 5. 宏任务中注册的宏任务:4小结
| 概念 | 说明 |
|---|---|
| 宏任务 | setTimeout setInterval I/O UI 渲染 |
| 微任务 | Promise.then/catch/finally MutationObserver |
| 执行顺序 | 同步 → 微任务 → 宏任务 → 微任务 → ... |
setTimeout(fn, 0) | 最快也要等当前同步+微任务完成后执行 |
上一节:async/await 与错误处理 下一节:模块化
