Skip to main content

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:

  1. console.log('1') runs immediately. -> logs 1.
  2. setTimeout(...) makes the browser set a timer. Once the timer fires, the callback goes into the task queue, rather than running right away.
  3. console.log('3') runs. -> logs 3.
  4. Once the call stack is empty, the Event Loop takes the task from the queue (the setTimeout callback) and puts it on the stack. -> logs 2.

Console output:

javascript
1 3 2

Task queue vs microtasks

JavaScript has two queues:

Queue typeSource of tasksWhen they run
Task Queue (macro tasks)setTimeout, setInterval, DOM events, an errored fetch.then, and so onAfter the stack and all microtasks are cleared
Microtask QueuePromise.then, queueMicrotask, MutationObserverRight 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 B

Explanation:

  • A, D run immediately (call stack).
  • C is a microtask, runs right after the stack clears.
  • B is a macrotask, runs after all microtasks.

Summary

TermDescription
Task QueueThe macrotask queue - holds callbacks from setTimeout, events, and so on
Microtask QueueThe microtask queue - for Promise.then, queueMicrotask
Event LoopThe mechanism that watches the stack and the queues and decides what to run next
OrderThe stack runs first -> microtasks -> macrotasks

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.