Skip to content

事件循环

Call stack, 任务 queue, microtasks, and 如何 JavaScript schedules asynchronous 工作.

你将学到

  • 单个-threaded call stack and 如何 frames 推送 and pop
  • Macrotasks (setTimeout, setInterval, I/O) and 任务 queue
  • Microtasks (Promise 回调, queueMicrotask) and 它们的 priority
  • 为什么 microtasks 运行之前下一个 macrotask
  • 如何 requestAnimationFrame fits 到渲染流水线

概念讲解

Single Thread, One Stack

JavaScript runs on a single call stack — it executes one statement at a time. When a function is called, a frame is pushed onto the stack; when it returns, the frame pops. If a slow operation ran on this stack, the entire page would freeze. The event loop exists to keep the stack free by offloading slow work to the host environment (browser or Node) and running the callback later.

Macrotask Queue

When an async operation finishes (a timer fires, a network response arrives, a file read completes), its callback is placed in the macrotask queue (also called the task or callback queue). After the call stack is empty, the event loop takes one macrotask from the queue and runs it to completion. Then it checks for microtasks before taking the next macrotask.

Microtask Queue

Promise callbacks (.然后, .catch, 等待 continuations) and queueMicrotask() go into the microtask queue. Microtasks have higher priority: after every macrotask, the event loop drains the entire microtask queue before rendering or taking the next macrotask. This is why a resolved promise's 然后 runs before a setTimeout(fn, 0) — the timer is a macrotask, the promise is a microtask.

The Ordering in Practice

This ordering has real consequences. A long chain of microtasks can starve the macrotask queue, delaying timers and I/O. Conversely, heavy macrotasks block rendering. Understanding the distinction explains many "为什么做这个运行首先?" puzzles and is essential for writing correct async code.

requestAnimationFrame

For visual updates, requestAnimationFrame schedules a callback right before the browser repaints — typically ~60 times per second. It runs in a dedicated phase between microtask draining and rendering, making it the correct choice for animations. Using setTimeout for animations can cause jank because it is not synced with the display refresh.

Concurrency Without Threads

The event loop gives JavaScript concurrency (overlapping I/O) without parallelism (simultaneous execution). For true CPU parallelism, use Web Workers (browser) or worker_threads (Node). The event loop is about never blocking the single thread, not about running two things at the exact same instant.

示例代码

              console.log("1. script start");

// Macrotask — setTimeout goes in the task queue
setTimeout(() => {
  console.log("4. setTimeout (macrotask)");
}, 0);

// Microtask — promise.then runs before the next macrotask
Promise.resolve().then(() => {
  console.log("3. promise (microtask)");
});

console.log("2. script end");
// Output order: 1, 2, 3, 4 — microtask beats macrotask

// Microtasks drain completely before the next macrotask
Promise.resolve()
  .then(() => console.log("micro 1"))
  .then(() => console.log("micro 2"))
  .then(() => console.log("micro 3"));
setTimeout(() => console.log("macro after all micros"), 0);

// queueMicrotask — explicit microtask scheduling
queueMicrotask(() => console.log("queued microtask"));

// requestAnimationFrame — synced with rendering
let frame = 0;
function animate() {
  console.log("frame", frame);
  if (++frame < 3) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

// A long microtask chain delays macrotasks (starvation)
async function starvationDemo() {
  for (let i = 0; i < 3; i++) {
    await Promise.resolve(); // microtask
    console.log("await", i);
  }
  console.log("microtasks done");
}
starvationDemo();
            

Demonstrates classic script→microtask→macrotask 排序, microtask queue draining, queueMicrotask, requestAnimationFrame for 渲染, and 如何链 的 awaits (microtasks) 运行之前 setTimeout (macrotask).

动手试一试

常见错误

错误写法

Assuming setTimeout(fn, 0) 运行 immediately 之后 current code

正确做法

setTimeout 是 macrotask. Promise 回调 (microtasks) 总是运行之前下一个 macrotask. 如果你 需要到 运行 code 正确之后 current synchronous 块, use queueMicrotask() or Promise.resolve().然后().

错误写法

创建无限 microtask 循环那个 starves 事件循环

正确做法

因为 microtask queue 是 fully drained 之前任何 macrotask, endless 链的 microtasks (e.g. recursive .然后) prevents timers and I/O 从运行. Break 长工作到 macrotasks 使用 setTimeout 到 yield control.

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误