Workspace

The event loop, tasks and microtasks

3 day streakD

The event loop, tasks and microtasks

JavaScript runs one piece of code at a time and picks the next piece from queues. Learn the order: synchronous code, then every microtask, then the next task.

BasicsLesson 2 of 614 min

Node and browsers run JavaScript on one thread with an event loop. The loop takes one task from a queue, runs it to completion, then drains the microtask queue completely, then takes the next task. Nothing interrupts running code. Concurrency comes from interleaving many short tasks, not from running them at the same moment.

  • Tasks (macrotasks): timer callbacks, I/O callbacks, setImmediate, and in browsers, events and messages.
  • Microtasks: promise reactions (.then, the code after an await) and queueMicrotask. In Node, process.nextTick callbacks run even before promise microtasks.
Figure 2.1

Run five lines and predict the output

1console.log("A");
2setTimeout(() => console.log("B"), 0);
3Promise.resolve().then(() => console.log("C"));
4queueMicrotask(() => console.log("D"));
5console.log("E");
Call stack
  1. main script
Microtask queueempty
Task queueempty
Console…

The whole script is one task. It runs to completion before anything else.

Step 01 / 9
Step through the code. Synchronous lines run first. Promise and queueMicrotask callbacks wait in the microtask queue and run as soon as the stack empties. The timer callback is a task, so it runs last even with a 0 ms delay.

Node's loop phases

libuv runs Node's loop in phases: timers (expired setTimeout), pending callbacks, poll (wait for I/O and run its callbacks), check (setImmediate) and close callbacks. Microtasks drain between every callback. The poll phase is where the process sleeps in epoll_wait or kqueue when there is nothing to do.

yield.tsTypeScript
// Process 100,000 items without freezing other requests
async function processAll(items: Item[]) {
  for (let i = 0; i < items.length; i++) {
    handle(items[i]);
    if (i % 1000 === 0) {
      // Yield to the event loop: a real task boundary, not a microtask
      await new Promise((resolve) => setImmediate(resolve));
    }
  }
}
// Note: `await Promise.resolve()` would NOT yield to I/O.
// It only queues a microtask, which runs before any task.

In browsers, scheduler.yield() serves the same purpose and keeps the task's priority.

Where you will meet it

Streaming UIs

React batches state updates and the browser paints between tasks. A chat UI that processes tokens in one long microtask chain cannot paint until it finishes (Module 11).

Health checks

A Node server whose loop is blocked cannot answer its health check, so the orchestrator restarts it while it is merely busy.

Measuring lag

perf_hooks.monitorEventLoopDelay() reports how late the loop runs callbacks. Alert on its p99, not CPU.

Check yourself

Answer out loud before you open each one.

What does await do relative to the event loop?

It suspends the async function and resumes it in a microtask once the awaited promise settles.

Why does setTimeout(fn, 0) run after a resolved promise's .then?

The timer callback is a task. All microtasks drain before the loop takes the next task.

How do you yield to I/O in the middle of a long loop in Node?

Await a task boundary such as setImmediate, not a resolved promise.

Try it

Add process.nextTick, setImmediate and setTimeout(..., 0) to the example, run it in Node, and explain the order. Then run it inside an I/O callback and see setImmediate beat the timer.

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap