Back to results for “Async”
Node.js › Event Loop & Non-blocking IO

What is a callback queue (or task queue) in the context of the Node.js event loop, and how does it relate to the call stack?

Beginner

Answer

The call stack is where JavaScript's currently executing synchronous code lives, executed one frame at a time. When an asynchronous operation completes, its associated callback isn't executed immediately -- it's placed into an appropriate queue (a macrotask queue for things like I/O and timers, or the microtask queue for promises), and the event loop only moves a queued callback onto the call stack once the stack is completely empty, ensuring currently running synchronous code always finishes before any queued asynchronous callback begins.
console.log('1');
setTimeout(() => console.log('3'), 0); // queued, waits for the call stack to empty
console.log('2');
// Output: 1, 2, 3 -- the setTimeout callback only runs once the synchronous code finishes
// and the call stack is empty, even with a 0ms delay
Real-world example A developer confused why a setTimeout(fn, 0) callback doesn't run immediately learns that it's placed in a queue and can only execute once the call stack is completely empty, which is why any additional synchronous code after the setTimeout call still runs first, regardless of the specified delay.

Common follow-ups: Why does even a 0ms setTimeout still get queued rather than running synchronously and immediately?;How many different queues does Node.js actually have, given microtasks and macrotasks are handled somewhat differently?