The event loop: how JavaScript handles waiting
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- Final project: a post explorer with modules and fetch
One thread, many waiting jobs
JavaScript runs your code on a single thread. That means it does one thing at a time. Yet a web page can wait for a network response, run a timer and react to clicks all together without freezing. The mechanism that makes this possible is the event loop. If async code ever surprised you, this lesson is the explanation.
The call stack
When you call a function, JavaScript puts it on the call stack. When the function returns, it comes off. The engine always runs whatever is on top.
function third() { console.log("third"); }
function second() { third(); }
function first() { second(); }
first();
The stack grows to first, second, third, then shrinks back. Synchronous code means each line finishes before the next starts. If one function takes five seconds, nothing else can run for five seconds. In a browser the page cannot respond to clicks during that time.
Async work lives outside the stack
Timers, network requests and file reads are not done by JavaScript itself. The browser (or Node) does them in the background. When one finishes, it puts your callback into a queue. The event loop's job is simple: whenever the call stack is empty, take the next callback from a queue and push it onto the stack.
There are two queues you need to know:
- The task queue (macrotasks). Timers such as
setTimeout, and events such as clicks, go here. - The microtask queue. Promise callbacks (
.then, and what followsawait) go here.
After each task finishes, and whenever the stack is empty, the engine runs all the microtasks before it takes the next task. So promises always get ahead of timers.
Predict the output
This is the example I like to use to test myself:
console.log("1: start");
setTimeout(() => {
console.log("2: timeout");
}, 0);
Promise.resolve().then(() => {
console.log("3: promise");
});
console.log("4: end");
The output is:
1: start
4: end
3: promise
2: timeout
Walk through it. Line one prints immediately. setTimeout hands its callback to the timer system, which will queue it as a task. The promise callback goes on the microtask queue. Then "4: end" prints, and the main script is done, so the stack is empty. The event loop runs the microtask first, printing "3: promise". Only then does it take the timer task and print "2: timeout".
Even with a delay of 0, the timeout callback runs after all synchronous code and after all promise callbacks. A zero delay means "as soon as possible after the current work", not "now".
Blocking the loop
Because everything shares one thread, a long loop blocks the whole page:
const start = Date.now();
while (Date.now() - start < 3000) {
// busy for three seconds
}
console.log("done");
During those three seconds a browser tab cannot repaint or handle clicks, and a Node server cannot answer anyone. This is why we avoid heavy computation on the main thread. The options are to split the work into smaller chunks, use a Web Worker in the browser, or use a worker thread in Node.
Timers are not exact
setTimeout(fn, 1000) does not run fn at exactly one second. It means "no earlier than one second from now". If the stack is busy at that moment, the callback waits:
const t0 = Date.now();
setTimeout(() => console.log("waited", Date.now() - t0, "ms"), 100);
const spin = Date.now();
while (Date.now() - spin < 500) {}
Here the callback runs after about 500 ms, not 100, because the loop held the thread. The timer was ready, but the stack was not empty.
Where the browser fits in
In the browser there is one more queue to know about. Before the screen repaints, the browser runs requestAnimationFrame callbacks. Rendering happens between tasks, so a long task also delays painting. It is one more reason to keep each piece of work short.
Microtask starvation
Microtasks all run before the next task, including microtasks that are added by microtasks. A promise that keeps scheduling itself will never let the timer or the click handler in:
function loop() {
Promise.resolve().then(loop); // never gives way to other tasks
}
// loop(); // do not run this, it freezes the tab
It is rare in real code, but it explains why "promises are always faster" is not a good rule. Fair handling is the job of tasks.
Why this matters for your code
- Code after an
awaitor in a.thennever runs in the same turn as the code that started it. - Order bugs, such as reading a value before it has loaded, come from forgetting that callbacks run later.
- UI freezes usually mean a long synchronous job on the main thread.
setTimeout(fn, 0)is a way to say "run this after the current code and any promises".
Common mistakes
- Assuming code runs in the order it is written. Async callbacks run later, in queue order.
- Using a busy loop to wait. Use a timer or a promise.
- Expecting setTimeout to be precise. It is a minimum, not a guarantee.
- Forgetting microtasks beat timers. Promise callbacks always run before the next timeout.
- Running heavy loops on the main thread. Break up the work or use a worker.
Try it yourself
- Predict the output of the example, then change the timeout to 100 and see whether anything changes.
- Add a second
Promise.resolve().then(...)and a secondsetTimeout. Predict the exact order of all six lines. - Write a loop that does
console.log(i)insidesetTimeout(..., 0)forifrom 1 to 3, and print "sync done" after the loop. Explain the result. - In the browser console, run the busy loop for three seconds and try to click on the page.
console.log("1: start");
setTimeout(() => {
console.log("2: timeout");
}, 0);
Promise.resolve().then(() => {
console.log("3: promise");
});
console.log("4: end");
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account