Section 1: How async JavaScript works
The event loop in plain words
The event loop is the mechanism that decides which piece of code runs next. You do not need every detail of the specification, but a simple model explains almost all real behaviour.
The pieces
- The call stack holds the functions currently running. JavaScript runs whatever is on top until the stack is empty.
- The task queue (also called the macrotask queue) holds callbacks from timers, user events, network events and similar sources.
- The microtask queue holds promise callbacks (
then,catch,finally, and the continuation after anawait) andqueueMicrotaskcallbacks.
The loop
In a simplified form:
- Run the current script until the call stack is empty.
- Run all microtasks, including any new microtasks added while running them.
- Let the browser render if needed.
- Take one task from the task queue and run it. Then go back to step 2.
Predicting the order
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
queueMicrotask(() => console.log("D"));
console.log("E");
The output is A, E, C, D, B. The synchronous logs run first. Then the microtask queue is emptied in order: C, then D. Only after that does the timer task run, printing B.
This is why a promise callback always runs before a setTimeout(..., 0) callback that was scheduled at the same time.
Why it matters
- Long synchronous code blocks everything, including rendering and other callbacks. Break heavy work into chunks or move it to a Web Worker.
- Endless microtasks starve the page. If a promise callback keeps scheduling more promise callbacks, rendering never happens.
- Timers are a minimum delay, not a guarantee.
setTimeout(fn, 100)means "not before 100 ms", and it can be much later if the main thread is busy.
Node.js
Node.js uses the same idea with extra phases for I/O, timers and immediate callbacks, and process.nextTick runs even before promise microtasks. The core model above still holds for most code you will write.
Exercise: before running them, write down the order of five mixed examples in the course repository, then run them and compare.