Sub topic 1
Why JavaScript Needs Asynchronous Code: The Event Loop
JavaScript runs your code on a single thread. One thread means one call stack, and only one piece of code can run at any moment. Many tasks still involve waiting: network requests, disk reads, timers, user clicks. If JavaScript sat idle during each wait, a web page would freeze and a server would handle one request at a time. The event loop prevents that. It is the mechanism that lets one thread start slow operations, keep running other code, and come back when the results are ready.
This chapter builds the working model that the rest of the tutorial depends on. Promises, async functions, and await all sit on top of the event loop, and each of them makes more sense once you can picture where your code waits and when it runs.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, including arrow functions
- Callbacks and higher-order functions (passing a function to another function)
- Basic
try/catch/finally - Running scripts in Node.js or a browser console
You do not need to know Promises yet. They come in the next chapter.
The Single-Threaded Model
The call stack
The call stack records which functions are currently running. Calling a function pushes a frame onto the stack. Returning pops it off. The engine only ever executes the frame on top of the stack.
function square(n) {
return n * n;
}
function printSquare(n) {
const result = square(n);
console.log(result);
}
printSquare(4); // 16While this runs, the stack grows to printSquare → square, shrinks back to printSquare, briefly holds console.log, then empties. Everything here is synchronous: each line finishes before the next one starts.
Run-to-completion
JavaScript gives you a guarantee called run-to-completion. Once a function starts, nothing else in your JavaScript can interrupt it. No timer callback or click handler can jump in halfway through. Other work runs only after the call stack is empty.
This guarantee makes JavaScript easier to reason about than many multithreaded languages, because you do not need locks to protect shared variables. It has a cost: a long-running function holds up everything else.
What Blocking Looks Like
The code below keeps the thread busy for two seconds with a busy-wait loop:
function blockFor(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {
// spin: the thread can do nothing else
}
}
console.log('start');
setTimeout(() => console.log('timer fired'), 0);
blockFor(2000);
console.log('end');Output:
start
end
timer firedThe timer asked for a delay of 0 ms, but its callback ran only after about two seconds. The callback had to wait for the call stack to empty, and blockFor kept it full. In a browser, the same loop would also freeze scrolling, typing, and rendering for those two seconds. In Node.js, a server would accept no new requests during that time.
The Pieces of the Event Loop
If JavaScript has one thread, how does it run a 2-second network request without blocking? The engine does not do the waiting itself. The host environment does: the browser or Node.js. The host provides APIs (timers, fetch, file system, sockets) that run outside your JavaScript thread, for example in the operating system or in native threads.
The model has four parts:
| Part | What it does |
|---|---|
| Call stack | Runs your JavaScript, one frame at a time |
| Host APIs | Timers, network, disk, and events, handled outside the JS thread |
| Task queue | Holds callbacks that are ready to run, in order |
| Event loop | When the stack is empty, takes the next task from the queue and runs it |
The flow works like this:
- Your code calls a host API such as
setTimeout(callback, 100). - The host registers the timer and returns immediately. Your code keeps running.
- When the timer expires, the host places
callbackin the task queue. - When the call stack is empty, the event loop takes
callbackfrom the queue and pushes it onto the stack.
The word "loop" is literal. The host repeats this cycle for as long as the program runs: run a task to completion, check the queue, run the next task. In a browser, rendering also happens between tasks. That is why a blocking task prevents the screen from updating.
Tracing a Non-Blocking Program
Here is a program with two timers:
console.log('1: script start');
setTimeout(() => {
console.log('4: timeout A (100 ms)');
}, 100);
setTimeout(() => {
console.log('3: timeout B (0 ms)');
}, 0);
console.log('2: script end');Output:
1: script start
2: script end
3: timeout B (0 ms)
4: timeout A (100 ms)Step by step:
- The whole script runs as the first task. It logs line 1, registers two timers, and logs line 2.
- The script finishes and the stack empties.
- Timer B expires almost immediately. Its callback enters the queue, and the event loop runs it.
- About 100 ms later, timer A's callback enters the queue and runs.
Real I/O: Doing Other Work While Waiting
Timers show the mechanics, but the real benefit appears with I/O. Compare a synchronous and an asynchronous file read in Node.js. Save this as read-demo.js and run it with node read-demo.js. It reads its own source file, so no other files are needed.
const fs = require('fs');
console.log('sync: before');
const text = fs.readFileSync(__filename, 'utf8');
console.log(`sync: read ${text.length} characters`);
console.log('sync: after');
console.log('async: before');
fs.readFile(__filename, 'utf8', (err, data) => {
if (err) {
console.error('async: read failed', err);
return;
}
console.log(`async: read ${data.length} characters`);
});
console.log('async: after');Output:
sync: before
sync: read 512 characters
sync: after
async: before
async: after
async: read 512 charactersThe character count depends on your file. The order is what matters. readFileSync blocks the thread until the disk returns data. readFile hands the work to Node's I/O layer and returns at once, so async: after prints before the data arrives. The callback runs later, as its own task.
Timer Delays Are Minimums
The delay you pass to setTimeout is the earliest time the callback can be queued. It does not guarantee when the callback runs. If the stack is busy, the callback waits:
function blockFor(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {}
}
const t0 = Date.now();
setTimeout(() => {
console.log(`asked for 100 ms, got ${Date.now() - t0} ms`);
}, 100);
blockFor(500);This prints something like asked for 100 ms, got 501 ms. Hosts can add further delay. Browsers clamp deeply nested timers to at least 4 ms, and background tabs may throttle timers to once per second or less often.
Keeping the Loop Responsive
CPU-heavy work cannot be made faster by the event loop, because it really does need the thread. You have two main options.
The first option is to split the work into chunks and yield between them, so other tasks get a turn:
function sumInChunks(n, chunkSize, onDone) {
let total = 0;
let i = 0;
function runChunk() {
const stop = Math.min(i + chunkSize, n);
for (; i < stop; i++) {
total += i;
}
if (i < n) {
setTimeout(runChunk, 0); // yield to the event loop
} else {
onDone(total);
}
}
runChunk();
}
sumInChunks(50_000_000, 1_000_000, total => {
console.log('total:', total);
});
console.log('started; the loop stays free between chunks');The second option is to move the work to another thread with Web Workers in the browser or worker_threads in Node.js. Workers run in parallel and communicate by passing messages. They are the right tool when the computation is long and cannot be split up easily.
Why Callbacks Are Not Enough
Every async API in this chapter reports its result through a callback. That works, but it causes trouble as programs grow:
const fs = require('fs');
fs.readFile(__filename, 'utf8', (err, first) => {
if (err) return console.error(err);
fs.readFile(__filename, 'utf8', (err2, second) => {
if (err2) return console.error(err2);
setTimeout(() => {
console.log('both reads done:', first.length + second.length);
}, 100);
});
});Each dependent step adds a level of nesting. Every level needs its own error check, and you cannot use try/catch around the outer call, because the callbacks run in later tasks after the try block has already exited. You also cannot return a result to the original caller. The value only exists inside the callback.
Promises fix this by representing a future result as an object you can return, pass around, and chain. async and await then let you write that chaining as straight-line code. Neither one changes the event loop. They are a cleaner way to schedule work on it.
Common Mistakes
| Mistake | What actually happens | Fix |
|---|---|---|
| Expecting `setTimeout(fn, 0)` to run `fn` immediately | `fn` runs after the current code and any earlier queued tasks | Treat it as "run later" and put dependent code inside the callback |
| Reading a callback's result right after starting the operation | The variable is still unset, because the callback has not run yet | Use the value inside the callback, or use Promises and `await` |
| Wrapping an async call in `try/catch` to catch its errors | Errors in the later callback escape the `try` block | Handle errors in the callback, or use `await` inside `try` |
| Running heavy loops on the main thread | UI freezes and server requests stall | Chunk the work or use a worker |
| Treating timer delays as exact | Callbacks run late when the stack is busy or the host throttles | Measure elapsed time with `Date.now()` or `performance.now()` |
Exercises
Exercise
Predict the output order of this code and explain it: console.log('x'); setTimeout(() => console.log('y'), 0); for (let i = 0; i < 1e8; i++) {} console.log('z');
Show answer
The output is x, z, y. The loop and both synchronous logs run in the current task. The timer callback can only run after the call stack is empty, even with a 0 ms delay and however long the loop takes.
Exercise
A colleague writes: let data; fs.readFile('config.json', 'utf8', (err, text) => { data = text; }); console.log(data.length); Why does this throw, and how should it be restructured with callbacks?
Show answer
readFile returns immediately and its callback runs in a later task, so data is still undefined when console.log runs, and reading .length on undefined throws a TypeError. Move the code that uses the data into the callback: fs.readFile('config.json', 'utf8', (err, text) => { if (err) return console.error(err); console.log(text.length); });
Exercise
A browser page computes a report in one loop that takes 3 seconds, and the page cannot be scrolled during that time. Name two ways to fix this and one trade-off of each.
Show answer
First, split the loop into chunks and yield with setTimeout between them. This keeps the page responsive, but the total time grows slightly and the code gets more complex because state must survive between chunks. Second, run the computation in a Web Worker. This uses a separate thread and leaves the main thread free, but data has to be sent by message passing, and workers cannot touch the DOM.