What is the task queue?
The task queue is a data structure that holds tasks (callbacks) waiting to run once the call stack has cleared. It is a key element of the Event Loop mechanism in JavaScript.
Key idea
JavaScript is a single-threaded language; it can execute only one task at a time.
While the engine is busy running functions on the call stack, other tasks, such as click handlers, setTimeout, fetch, and so on, wait their turn in the task queue.
When the call stack becomes empty, the Event Loop takes the first task from the queue and puts it on the stack, and this continues indefinitely.
Example
javascript
console.log('1');
setTimeout(() => {
console.log('2');
}, 0);
console.log('3');Step by step:
console.log('1')runs immediately. -> logs1.setTimeout(...)makes the browser set a timer. Once the timer fires, the callback goes into the task queue, rather than running right away.console.log('3')runs. -> logs3.- Once the call stack is empty, the Event Loop takes the task from the queue (the
setTimeoutcallback) and puts it on the stack. -> logs2.
Console output:
javascript
1
3
2Task queue vs microtasks
JavaScript has two queues:
| Queue type | Source of tasks | When they run |
|---|---|---|
| Task Queue (macro tasks) | setTimeout, setInterval, DOM events, an errored fetch.then, and so on | After the stack and all microtasks are cleared |
| Microtask Queue | Promise.then, queueMicrotask, MutationObserver | Right after the current task, before the next macrotask |
Example with microtasks
javascript
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');Output order:
javascript
A
D
C
BExplanation:
A,Drun immediately (call stack).Cis a microtask, runs right after the stack clears.Bis a macrotask, runs after all microtasks.
Summary
| Term | Description |
|---|---|
| Task Queue | The macrotask queue - holds callbacks from setTimeout, events, and so on |
| Microtask Queue | The microtask queue - for Promise.then, queueMicrotask |
| Event Loop | The mechanism that watches the stack and the queues and decides what to run next |
| Order | The stack runs first -> microtasks -> macrotasks |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.