Lesson 68 of 296
The event loop
What you will learn
- The call stack
- Web APIs (runtime APIs)
- The task queue and the microtask queue
- How the event loop decides what runs next
- Why
setTimeout(fn, 0)runs after promises - How to predict the order of logs
On this page
The four parts
| Part | Job |
|---|---|
| Call stack | Where JavaScript keeps track of the functions currently running |
| Runtime APIs | Browser or Node.js features that do work in the background: timers, network, events |
| Task queue (also called macrotask queue) | Callbacks waiting to run: timers, events, I/O |
| Microtask queue | Higher-priority callbacks: promise reactions (.then, await), queueMicrotask |
The call stack
The call stack is a list of the functions that are running right now. When a function is called, it is pushed on top. When it returns, it is popped off. JavaScript always runs whatever is on top of the stack.
function c() { console.log("c"); }
function b() { c(); }
function a() { b(); }
a();Stack over time:
a -> a,b -> a,b,c -> a,b -> a -> (empty)If functions keep calling each other without stopping (infinite recursion), the stack grows until you get "Maximum call stack size exceeded", a stack overflow.
Runtime APIs
When you call setTimeout, fetch or addEventListener, JavaScript hands the job to the runtime and immediately continues. The runtime does the waiting in the background. When the job is ready, it puts your callback in a queue.
The event loop
The event loop is the process that keeps everything moving. In simple terms:
- Run the current script until the call stack is empty.
- Run all microtasks in the microtask queue, one by one, until it is empty. (Microtasks added during this step also run now.)
- The browser may now render (update the screen).
- Take one task from the task queue and run it.
- Go back to step 2.
Key rule: after each task, all microtasks run before the next task. So promise callbacks always run before timer callbacks that were waiting at the same time.
Why setTimeout(fn, 0) runs after promises
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");Output:
1
4
3
2Step by step:
console.log("1")runs: prints 1.setTimeout: the runtime will queue the callback as a task (after at least 0 ms).Promise.resolve().then(...): the callback goes into the microtask queue.console.log("4")runs: prints 4.- The script is finished; the stack is empty.
- Run all microtasks: prints 3.
- Run the next task: the timer callback prints 2.
setTimeout(fn, 0) means "at least 0 ms, and only when the stack is empty and microtasks are done". It never runs immediately. Browsers also enforce a minimum delay of about 4 ms for deeply nested timers.
A harder example
console.log("start");
setTimeout(() => console.log("timeout 1"), 0);
Promise.resolve()
.then(() => console.log("promise 1"))
.then(() => console.log("promise 2"));
setTimeout(() => console.log("timeout 2"), 0);
queueMicrotask(() => console.log("microtask"));
console.log("end");Output:
start
end
promise 1
microtask
promise 2
timeout 1
timeout 2Why promise 2 is after microtask: the second .then is only queued when the first one finishes. At that moment, microtask is already in the queue ahead of it.
async functions and the event loop
Code in an async function runs synchronously until the first await. Everything after await runs later, as a microtask.
async function run() {
console.log("A");
await null;
console.log("B");
}
console.log("1");
run();
console.log("2");Output: 1, A, 2, B.
How to predict output: a method
- Run all synchronous code first, top to bottom. Write those logs down.
- Note where each callback goes: microtask (
then,await,queueMicrotask) or task (setTimeout,setInterval, events). - Empty the microtask queue in order, adding new microtasks to the end as they appear.
- Then run tasks one at a time, emptying microtasks after each one.
Why this matters in real code
- Long synchronous code freezes the page, because the event loop cannot reach step 3 (render) or handle clicks. Split heavy work into chunks, or move it to a Web Worker (a background thread) in the browser, or a worker thread in Node.js (Part 15).
- An endless chain of microtasks can also freeze the page, because rendering waits until the microtask queue is empty.
- In Node.js the event loop has more phases (timers, I/O callbacks,
setImmediate, andprocess.nextTick, which runs before promise microtasks), but the same main idea applies. Part 15 covers it.
Common mistakes
- Thinking
setTimeout(fn, 0)runs straight away. - Thinking promises run on another thread. They do not; only the waiting happens in the runtime.
- Forgetting that code before the first
awaitruns synchronously.
How to say it in an interview
"JavaScript runs on a single call stack. Async work like timers and network requests is handed to the runtime, which queues callbacks when ready. The event loop runs the current script until the stack is empty, then drains the entire microtask queue, which holds promise reactions, then the browser can render, then it takes one task from the task queue, such as a timer or event, and repeats. That is why a resolved promise's then runs before a setTimeout with zero delay. Long synchronous work blocks rendering and input, so I break it up or move it to a worker."
Key words
| Word | Meaning |
|---|---|
| Call stack | The list of functions currently running |
| Stack overflow | Error when the stack grows too large, usually endless recursion |
| Event loop | The process that moves callbacks from queues to the call stack |
| Task / macrotask | A callback from timers, events or I/O |
| Microtask | A higher-priority callback, mainly from promises |
| Runtime APIs | Browser or Node.js features that work in the background |
| Web Worker | A background thread in the browser |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.