事件循环(Event Loop)是 JavaScript 单线程模型的核心机制,也是前端面试必考题。理解它,你才能真正掌握 setTimeout、Promise、async/await 的执行顺序。

为什么 JavaScript 是单线程

JavaScript 设计之初是为了操作 DOM,如果多线程同时修改页面,浏览器会不知道该以谁为准。因此 JS 被设计为单线程执行,这也是它没有多线程竞争问题的原因。

调用栈(Call Stack)

JS 引擎(如 V8)维护一个调用栈,函数调用会被压入栈顶,执行完弹出。同步代码按顺序入栈出栈。

异步任务的两种队列

类型包含执行时机
宏任务 (MacroTask)setTimeout, setInterval, I/O, UI 渲染每次调用栈清空后取一个
微任务 (MicroTask)Promise.then, queueMicrotask, MutationObserver当前宏任务结束后,清空所有微任务

执行顺序

一次完整的事件循环 tick:

  1. 执行同步代码(调用栈)
  2. 调用栈清空后,清空所有微任务队列
  3. 执行一个宏任务
  4. 渲染页面(如有需要)
  5. 回到第 2 步

经典面试题

console.log('1');

setTimeout(() => console.log('2'), 0);

Promise.resolve().then(() => console.log('3'));

console.log('4');

输出顺序:1 → 4 → 3 → 2

更复杂的例子

async function async1() {
  console.log('A1');
  await async2();
  console.log('A2');
}
async function async2() { console.log('A3'); }

console.log('start');
setTimeout(() => console.log('timeout'), 0);
async1();
new Promise(resolve => {
  console.log('promise');
  resolve();
}).then(() => console.log('then'));
console.log('end');

输出:start → A1 → A3 → promise → end → A2 → then → timeout

关键点:await 后面的代码相当于 .then() 回调,进入微任务队列。

总结