Sub topic 1
Why JavaScript Needs Asynchronous Code: The Event Loop
JavaScript runs your code on a single thread. That thread can do one thing at a time. If one task takes a long time, such as waiting for a network response, everything else has to wait behind it. This chapter explains how the event loop lets JavaScript start slow work, keep running other code, and come back when the result is ready. Promises and async/await, covered in later chapters, are built on this model.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, including arrow functions
- Callbacks and higher-order functions
- Running JavaScript in a browser console or Node.js
The problem: one thread, slow work
The call stack is the list of functions currently running. JavaScript keeps executing whatever is on top of the stack until it is empty. While the stack is busy, nothing else runs: no clicks are handled, no screen updates happen, and no other callbacks fire.
You can see this by blocking the thread on purpose:
console.log('start');
setTimeout(() => console.log('timer fired'), 0);
const end = Date.now() + 2000;
while (Date.now() < end) {
// busy-wait for 2 seconds, blocking the thread
}
console.log('end');
// Output: start, end (after ~2 seconds), timer firedThe timer asked for a 0 ms delay, but its callback still ran after the 2-second loop. A callback cannot interrupt code that is already running. It can only run once the call stack is empty.
The working model
The runtime (the browser or Node.js) does slow work outside your JavaScript thread. Timers, network requests, and file reads are handed off to the host environment. When one finishes, the host puts its callback in a task queue. The event loop is a simple cycle:
- Run the current code until the call stack is empty.
- Take the next callback from the queue.
- Push it onto the stack and run it.
- Repeat.
Your code never waits idle for a slow operation. It registers what should happen later and returns, which leaves the thread free for other work.
Non-blocking in practice
Here is the same idea without the artificial busy loop:
function fakeRequest(callback) {
setTimeout(() => callback({ id: 1, name: 'Ada' }), 500);
}
console.log('requesting user');
fakeRequest(user => console.log('got user:', user.name));
console.log('doing other work');
// Output: requesting user, doing other work, got user: AdafakeRequest returns right away. The rest of the script runs, and the callback runs about 500 ms later, once the stack is empty and the timer has finished.
Common errors in this model
| Mistake | What happens | Fix |
|---|---|---|
| Expecting `setTimeout(fn, 0)` to run immediately | `fn` runs only after the current code finishes | Treat the delay as a minimum, not a guarantee |
| Reading a result right after starting async work | The value is still `undefined` | Use the result inside the callback (later, inside `.then` or after `await`) |
| Long synchronous loops in UI code | The page freezes | Split the work into chunks or move it to a worker |
Why callbacks are not the end of the story
Callbacks work, but chaining several dependent operations nests them deeper and deeper, and errors have to be passed by hand at every level. Promises give asynchronous results a standard object with clear states. async/await then lets you write that code in a top-to-bottom style. The event loop underneath stays the same. Later chapters also cover the microtask queue, a higher-priority queue that Promises use.
Exercise
Predict the output order of this code: console.log(1); setTimeout(() => console.log(2), 0); console.log(3); setTimeout(() => console.log(4), 0); console.log(5);
Show answer
1, 3, 5, 2, 4. The synchronous logs run first while the stack is busy. The two timer callbacks wait in the task queue and run in the order they were scheduled once the stack is empty.
Exercise
A button click handler runs a loop that takes 3 seconds. A user clicks a second button during that time. When does the second click's handler run, and why?
Show answer
It runs only after the 3-second loop finishes. The click event is queued as a task, and the event loop cannot take it from the queue until the call stack is empty.