The event loop: the whole lesson in words
Typing in the search box sometimes shows results for an older query.
Symptom
An agent wrote a search box. Type fast, and sometimes the results belong to an older query.
Out-of-order results usually mean out-of-order callbacks.
Predict
Before we explain anything, look at these four lines. In what order do they print?
Sync code
The script runs top to bottom on the call stack. Line one logs A straight away.
Synchronous code runs to completion first.
Web APIs
setTimeout doesn't run the callback. It hands it to the browser's timer, outside JavaScript.
Queues
The promise callback goes to the microtask queue, and line four logs D. Once the timer expires, the browser puts its callback in the task queue.
Two queues, two priorities.
Which first?
The stack is empty, and two callbacks are waiting. Which one does the loop pick first?
Microtasks drain
Every microtask runs before the next task. C prints, then the loop takes the timer callback, and B prints last.
Microtasks drain completely before the next task and before rendering.
Break it
Now change one line. Make the promise callback queue another microtask, forever, and watch the timer starve.
Endless microtasks block timers and paint.
Agent bug
Back to the search box. Each fetch callback runs when its response arrives, not when the request was sent. If the older query responds last, its results overwrite the newer ones.
Callbacks run in arrival order, so a stale response can win.
Recap
Sync code first, then every microtask, then one task, then repeat. The loop runs callbacks when they are queued, not when they were written, so the fix is to cancel or ignore stale ones.
Stack → all microtasks → one task → repeat.
The common wrong idea
setTimeout(fn, 0) runs fn immediately, before anything else that's queued.
What really happens
Callbacks wait in queues. After the current script finishes, every microtask runs before the next task (such as a timer callback).
The one-page cheatsheet for this lesson →