Event Loop: Callbacks from Readiness
The event loop turns readiness signals into callbacks, promises, and async/await progress.
A receptionist with two trays
Imagine a receptionist watching many doorbells. When one rings, she writes a note and puts it in a tray. Some notes are urgent and must be handled before the next normal note.
Memorable label: “Ready becomes queued.” The OS says something is ready. The runtime queues the matching work.
Six-year-old version: Toys yell “I’m ready!” The grown-up writes each toy’s name on a card, then reads the cards in order. Some tiny promise cards go first.
From I/O readiness to JavaScript work
Last lesson taught I/O multiplexing: one thread asks which sockets are ready. JavaScript adds a runtime rule: ready events become queued callbacks. A timer can queue onTimeout. A socket can queue onMessage. A resolved promise queues a microtask.
Task queue means normal callbacks. Microtask queue means promise reactions that run before the next normal task. MDN describes the browser event loop as processing tasks and microtasks (MDN event loop).
Demo: readiness becomes callbacks
Step through events. Notice that the promise microtask at time 2 runs before the timer task at the same time.
Runtime queues
Callback timeline
| Tick | Queue | Callback | Source |
|---|---|---|---|
| No callbacks yet. | |||
Exercise
node --test tests/event-loop.test.mjs Open src/event-loop.mjs. It models the key idea: sort readiness events, then choose microtasks before tasks at the same time.
Knowledge check
Interview payoff
Question: “How does async JavaScript relate to I/O multiplexing?”
Model answer: “The OS/runtime waits for I/O readiness across many sources. When something is ready, the runtime queues the matching callback, promise reaction, or async continuation. The event loop runs those units of work one at a time.”
Pro tip: Async does not mean your JavaScript runs in parallel. It means waiting is moved out of your function and resumed later by the event loop.
Next challenge: How does HTTP/2 use these same labels-and-frames ideas for web requests?