Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
A plain guide to the JavaScript runtime. You trace the call stack, see why setTimeout(fn, 0) runs last, learn why promise callbacks beat timers, and apply it in Node.js: worker threads for heavy work, batched API calls, and queueMicrotask over process.nextTick. The Node.js snippets were run in Node.js 22.

Why does setTimeout(fn, 0) not run right away? Why does a promise callback print before a timer that was set first? This guide answers both for developers who write async JavaScript and want to predict the order it runs in. You will trace the call stack, the task queue and the microtask queue with small examples, then apply the rules to Node.js code.
This is part 10 of the Frontend & JavaScript Fundamentals series. It follows essential Web APIs and browser concepts, which introduced the APIs that do the waiting described here.
Key takeaways
- JavaScript runs one job at a time on one call stack. A queued callback only runs once the stack is empty.
- After each task, the runtime empties the whole microtask queue (promise callbacks) before it takes the next task (timers, events).
- In Node.js, move heavy CPU work to a worker thread, and limit how many API calls you start at once.
What the event loop is
The event loop is the mechanism that takes queued jobs one at a time and runs each one to completion on the call stack. MDN's page on the execution model describes it as a job queue that is "generally first-in-first-out". Each job runs fully before the next one starts, so a running function is never interrupted by other JavaScript.
That model has three parts you can picture:
- The engine (V8, SpiderMonkey, JavaScriptCore) runs your code on a call stack.
- The host (a browser or Node.js) supplies timers, network calls and events. In Node.js, the libuv library does this work.
- The queues hold callbacks that are ready to run but waiting for the stack to clear.
The call stack
The call stack records where the program is right now. Calling a function pushes a frame onto the stack. Returning pops it off. MDN calls it last-in-first-out.
function multiply(x, y) {
return x * y;
}
function printSquare(x) {
const s = multiply(x, x);
console.log(s);
}
printSquare(5);
Here is the order of events:
- The script itself starts as the first job.
printSquare(5)is pushed.multiply(5, 5)is pushed, returns 25 and is popped.console.log(25)is pushed, runs and is popped.printSquareis popped, and the stack is empty again.
Because there is only one stack, a long loop or a heavy calculation keeps it busy. While it is busy, no click handler, timer or other callback can run. In a browser, the page can't repaint either. This is called blocking the event loop.
Where the waiting happens
When you call setTimeout, the engine does not count the milliseconds itself. It asks the host to start a timer and moves on to the next line. When the timer fires, the host puts your callback in the task queue. Network responses and user events work the same way.
The event loop then follows one rule: take the next job only when the call stack is empty. MDN's setTimeout page says it plainly: currently running code must finish before queued functions run.
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
console.log('End');
Output:
Start
End
Timeout
console.log('Start')runs and prints "Start".setTimeouthands a 0 ms timer to the host and returns at once.console.log('End')runs and prints "End".- The script ends and the stack is empty.
- The event loop takes the timer callback from the task queue, and it prints "Timeout".
A delay of 0 means "at the next opportunity", not "now". MDN also lists reasons a timer can fire later than asked. For example, browsers enforce a 4 ms minimum once nested setTimeout calls go five levels deep, and they slow timers in inactive tabs.
Microtasks run before the next task
There are two queues, not one. Promise callbacks go to the microtask queue. MDN's microtask guide gives the rule: each time a task finishes and no other JavaScript is running, the runtime runs every microtask in the queue. Only then does it take the next task. In a browser, it may also update the screen at that point.
| Queue | What goes in it | When it runs |
|---|---|---|
| Task queue | The script itself, setTimeout, setInterval, user events, and in Node.js I/O callbacks and setImmediate |
One task per turn of the loop |
| Microtask queue | Promise .then/await continuations, queueMicrotask(), MutationObserver |
Emptied completely after each task, before the next task |
Here is the classic interview question:
console.log('1: Script Start');
setTimeout(() => {
console.log('2: setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('3: Promise 1');
}).then(() => {
console.log('4: Promise 2');
});
console.log('5: Script End');
Output:
1: Script Start
5: Script End
3: Promise 1
4: Promise 2
2: setTimeout
- The two synchronous logs print first, because the script is the current task.
- The script ends. The runtime now empties the microtask queue, so "Promise 1" prints.
- When that callback returns, its promise settles. That queues the second
.thenas a new microtask. - The queue is not empty yet, so "Promise 2" prints in the same pass.
- Only now does the event loop take the next task, the timer, and "setTimeout" prints.
Microtasks can starve the page
Microtasks added while the queue is draining still run before the next task. MDN warns that adding them recursively can keep the event loop busy forever. Timers, clicks and screen updates then never get a turn, and the page freezes.
What this means for Node.js code
The same rules apply on a server. The Node.js event loop has phases (timers, poll for I/O, setImmediate checks, close callbacks), but every callback still runs on one stack.
Move heavy work off the main thread
A loop that crunches a large file blocks every incoming request until it finishes. The Node.js docs say worker threads are useful for CPU-heavy JavaScript and do not help much with I/O. Do the heavy part in a worker, not in the request handler:
// heavy.js: the main thread stays free while the worker counts
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', (sum) => console.log('Sum:', sum));
console.log('Main thread is still free');
} else {
let sum = 0;
for (let i = 0; i < 1e8; i++) sum += i;
parentPort.postMessage(sum);
}
"Main thread is still free" prints first, while the worker is still counting.
Control how many calls run at once
A common slip is await inside forEach. forEach ignores the promises your callback returns, so it neither waits nor runs the calls in order. Use for...of to run calls one at a time, or Promise.all on small batches to run a few at once.
const wait = (ms, label) =>
new Promise((resolve) => setTimeout(() => resolve(label), ms));
const ids = [1, 2, 3, 4, 5];
// Avoid: forEach does not wait for async callbacks
async function withForEach() {
ids.forEach(async (id) => {
await wait(10, id);
});
console.log('forEach returned before any wait finished');
}
// One at a time
async function oneByOne() {
for (const id of ids) {
await wait(10, id);
}
}
// In batches of two
async function inBatches(size = 2) {
for (let i = 0; i < ids.length; i += size) {
const batch = ids.slice(i, i + size);
await Promise.all(batch.map((id) => wait(10, id)));
}
}
withForEach().then(oneByOne).then(inBatches).then(() => console.log('done'));
Promise.all does not start anything. MDN's example marks each call as "already started when called": the work begins when you call the function that returns the promise. So Promise.all(ids.map(callApi)) fires every request at once. That can hit an API's rate limit, but it does not overflow the call stack. Batches, or a small library such as p-limit, keep the number in flight under control.
| Pattern | What runs at once | Trade-off | When to use |
|---|---|---|---|
for...of with await |
One call | Slowest, easiest on the API | Strict rate limits, or each call needs the last result |
Promise.all on batches |
One batch | Faster, still bounded | Most bulk API work |
Promise.all on everything |
Every call | Fastest, can trip rate limits | Small, known lists |
Prefer queueMicrotask over process.nextTick
process.nextTick callbacks run before promise callbacks in a CommonJS file. The Node.js docs now mark process.nextTick as legacy and recommend queueMicrotask() for most code, since it works the same in browsers and Node.js.
// Run in a CommonJS file
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
queueMicrotask(() => console.log('queueMicrotask'));
process.nextTick(() => console.log('nextTick'));
console.log('sync');
// sync, nextTick, promise, queueMicrotask, timeout
In an ES module the order of nextTick and the microtasks flips, which is one more reason to avoid relying on it.
Corrected in this version
The earlier version listed process.nextTick as a microtask, said microtasks run "after every single operation", and called UI rendering a macrotask. The text above follows the MDN and Node.js docs instead.
Summary
- Call stack: runs one frame at a time, last in, first out.
- Host APIs: timers, network and I/O wait outside the stack.
- Task queue: one task per turn of the loop.
- Microtask queue: emptied completely after every task.
- Event loop: when the stack is empty, drain microtasks, then take the next task.
Next in the series, JavaScript promises builds on the microtask queue to chain and combine async work.
Frequently asked questions
Why doesn't setTimeout with 0 ms run immediately?
The callback goes into the task queue, and the event loop only takes it once the current code has finished and the stack is empty. Any microtasks queued in the meantime run first. MDN also notes that browsers can delay timers further, for example in inactive tabs.
Do promise callbacks always run before setTimeout callbacks?
They run before the next task, so a promise that is already resolved beats a timer that was set in the same task. A promise that resolves later, for example after a network call, can of course run after a timer. The rule is about queues, not about which line comes first.
Is JavaScript really single-threaded?
Each JavaScript agent runs your code on one thread with one call stack. The host can use other threads for timers, I/O and workers. Web Workers and Node.js worker threads give you extra JavaScript threads, each with its own stack and event loop.
What is the difference between process.nextTick and queueMicrotask?
Both run soon after the current operation. In CommonJS, Node.js drains the nextTick queue first, then the microtask queue. The Node.js docs mark process.nextTick as legacy and recommend queueMicrotask() unless you need nextTick's specific behaviour.
How do I stop a long loop from freezing the page?
Move the work into a Web Worker, or split it into chunks and schedule each chunk with setTimeout so the browser gets a turn between them. Scheduling chunks as promise callbacks does not help, because the whole microtask queue runs before the browser can repaint.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...