Event loop mental model
Local practice: Node.js 22.16.0 on Linux x64; proposed teaching baseline 26.13.1 remains untested. Copy only the listed files into a fresh disposable directory. No dependency installation or external services required. These are static Node.js examples, not verified ByteMind runner tasks.
Run synchronous work before a timer callback
setTimeout(() => console.log('timer'), 0);console.log('start');console.log('end');Run:
node main.mjsExpected stdout:
startendtimerExit status: 0. Expected stderr: empty.
How it works
Think of an active call stack plus queues of work made ready by the runtime. In a simplified libuv cycle, timers handle eligible timers, pending callbacks handle certain deferred I/O callbacks, poll waits for and processes I/O, check handles setImmediate callbacks, and close callbacks handle some resource closures. Internal idle/prepare phases also exist. Promise microtasks and nextTick are not independent libuv phases. The model describes categories, not an exact timeline of every callback. Node 20 and newer use the libuv timer behavior introduced in 1.45: timers run after poll rather than both before and after it in the loop model.
Observe an I/O callback after the current stack
import { readFile } from 'node:fs';readFile('item.txt', 'utf8', (err, text) => { if (err) throw err; console.log('read:', text);});console.log('read requested');Run:
node main.mjsExpected stdout:
read requestedread: bookExit status: 0. Expected stderr: empty.
Common mistake
Do not assume asynchronous means immediate or parallel execution of JavaScript. Avoid universal top-level timeout versus immediate ordering claims; context and I/O readiness matter.
Practice
Move the synchronous log after the timer registration. Explain why it still precedes the timer. Identify the point where the file read hands control back to the runtime.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Event loop mental model — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
Which phase is associated with setImmediate?
Can a timer callback interrupt a running JavaScript callback on the same isolate?
Is a promise job a libuv phase?