← Runtimes
Runtimes

The event loop and queued work

Use queue boundaries to reason about order and responsiveness.

Reason about callback execution from the queue boundary and the context that scheduled it.

Outcome

Predict the order in which Node runs synchronous code, microtasks and macrotasks, explain how state changes between awaits on a single thread, and yield so that timers and I/O are not starved.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Event loop
The Node host mechanism that polls for events and runs callbacks through phases such as poll, check and timers. This lesson uses one JavaScript agent; Node can also use workers and native threads.
Macrotask
An informal label for host callbacks such as timers or I/O completions. Node has several phase queues, rather than a single standard macrotask queue.
Microtask
A promise reaction or queueMicrotask callback. A microtask checkpoint drains the queue, including newly queued microtasks, before returning control to the host loop.
process.nextTick
A Node-specific callback queue. At the native callback boundary used here it drains before microtasks; ESM evaluation and callbacks scheduled within a running microtask have different ordering contexts.
Starvation
Ready work is delayed because other work keeps control. An unbounded chain of microtasks can indefinitely postpone host timer and I/O callbacks.
Interleaving
Async continuations execute between one another’s suspension and resumption, allowing shared state to change across an await. This is distinct from simultaneous execution on multiple threads.

Callbacks, queues, and execution turns

A callback is code registered to run when its host schedules it; an asynchronous continuation is the code that resumes after a suspended operation. Registering either does not interrupt the JavaScript currently running on this agent. Ready work waits until execution reaches a boundary where the host or a microtask checkpoint can select it.

Node coordinates several queues and phases. To reason about an order, identify where work was queued and the context that is currently executing. To reason about responsiveness, also account for how much synchronous work runs before control reaches the next boundary. A timer delay alone answers neither question.

01Queues and turns

One thread, several queues

The seat service reports a reservation before its save finishes. Group bookings then expose an overlapping check and update, and a bulk import keeps ready save callbacks waiting. The maintainer needs to identify where another request can run and where the process must return control to Node.

This process runs application JavaScript on one agent. The probe schedules its callbacks inside readFile’s I/O callback. After that callback returns, Node drains its nextTick queue and then its microtasks. Promise reactions and queueMicrotask callbacks use the same queue, in enqueue order. The setImmediate callback is reached in check before the timer scheduled from this I/O callback. A timer’s delay is an eligibility threshold, not an appointment.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { readFile } from 'node:fs';

readFile(process.argv[1]!, () => {
  setTimeout(() => console.log('timeout'), 0);
  setImmediate(() => console.log('immediate'));
  Promise.resolve().then(() => console.log('promise'));
  queueMicrotask(() => console.log('microtask'));
  process.nextTick(() => console.log('nextTick'));
  console.log('sync');
});
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
Inside this readFile I/O callback, in which order do the six lines print?

02Interleaving at await

Single-threaded code can still race

A JavaScript async function executes its initial synchronous code at the call. At await it schedules a later continuation, even for an already fulfilled value. Two calls can therefore both observe an available seat before either continuation records its reservation. No simultaneous JavaScript execution is required for this logical race.

Two book(seat) calls start in the same turn. Each checks availability, awaits a still-pending save promise, then marks the seat taken. Can both succeed?

03Starving the loop

Yielding to microtasks does not let timers run

A long synchronous chunk keeps callbacks waiting. A chain of await null or fulfilled-promise awaits resumes through microtasks, so the importer can finish its whole chain before Node gets back to timers. A host callback such as setImmediate provides an opportunity to return to the loop. It does not guarantee that every pending I/O operation is ready or finished. The amount of work before each such return also matters: choosing the right queue cannot rescue an excessively long chunk.

A 500 ms import loop does await Promise.resolve() every few rows. A 20 ms timer was set just before it started. When does the timer callback run?

04Practice

Book seats on one thread

The lab uses a process-local reservation map and a 20 ms timer as its save model; no database or network is contacted. Bookings and import work interleave on one agent. The report checks the authored200 ms booking budget; OS scheduling and other work can still add delay. Its import-done line is a stable joined status, not an event-order trace.

The seat-booking service

Concurrent booking requests on one JavaScript thread. Report after saving, reserve groups without partial claims, then keep cheap and costly import rows from starving the bookings.

  1. easy · R-LOOP-V4-1 Report after saving
  2. medium · R-LOOP-V4-2 One seat, one user
  3. hard · R-LOOP-V4-3 Let timers run
Check this idea later
setTimeout(a, 0); Promise.resolve().then(b); Which runs first?
An async handler reads a balance, awaits a fraud check, then writes balance - amount. Two withdrawals arrive together. What can happen?
A CPU-heavy loop must let incoming HTTP requests be handled between chunks. Which yield works?
Sources
In the frontend A microtask checkpoint and a browser paint are different boundaries. Optional

An import progress bar updates after each synchronous row. The developer adds an await so the user can see progress. Review whether these waits establish an opportunity for input handling or paint during a long import; parseOne is a supplied synchronous row operation.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
'use client';

import { useState } from 'react';

export default function ImportProgress({
  rows,
  parseOne
}: {
  rows: number;
  parseOne: (row: number) => void;
}) {
  const [completed, setCompleted] = useState(0);

  async function run() {
    for (let row = 0; row < rows; row++) {
      parseOne(row);
      setCompleted(row + 1);
      await Promise.resolve();
    }
  }

  return (
    <>
      <button onClick={run}>Import</button>
      <progress aria-label="Import progress" value={completed} max={rows}></progress>
    </>
  );
}

setCompleted queues state updates; an already-fulfilled promise resumes through microtasks. These awaits do not establish a host-task or rendering opportunity between rows.

The source makes no promise about how many intermediate React commits or browser paints occur. It asks where control must return and how much synchronous work may precede that boundary.

Sources: React: queueing state updates,Svelte: tick,HTML: event-loop processing and rendering opportunities.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.