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.
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');
});
npx tsc --noEmit --strict main.ts && node main.ts
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.
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.
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.
Check this idea later
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.
'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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?