Sub topic 4
The Task Queue
This chapter assumes you know the call stack and how host APIs such as timers and network requests do their work outside the JavaScript engine. You should also be comfortable reading callbacks. The question here is what happens once a host API finishes its work and has a callback ready to run.
The answer is that the callback does not run right away. The host wraps it in a task and puts that task in a task queue. The callback runs only after the engine has finished everything it is doing now. This chapter covers what a task is, where tasks come from, the order they run in, and the mistakes people commonly make about them.
What a Task Is
A task is a unit of work that the host schedules to run later, starting on an empty call stack. Each task holds a callback and enough context to call it. Browser documentation and the HTML specification call these "tasks." Many articles call them "macrotasks" to set them apart from microtasks, which a later chapter covers. Both names mean the same thing.
A task has three properties that matter in practice:
- It starts on an empty call stack. A task never interrupts code that is already running. It waits until the stack is clear.
- It runs to completion. Once a task's callback starts, it runs until it returns or throws. No other task can cut in partway through.
- It is ordered. Tasks from the same source run in the order they were queued (first in, first out).
Your script itself also runs as a task. When the browser loads a <script> element, or when Node.js runs your entry file, the whole top-level script runs as one task. That is why the callbacks you schedule during startup cannot run before the script finishes.
Where Tasks Come From
Many parts of the host can queue tasks. The table lists the usual sources.
| Task source | Example API or event | Environment |
|---|---|---|
| Script execution | Running a `<script>` or the Node.js entry file | Both |
| Timers | `setTimeout`, `setInterval` | Both |
| User interaction | Real clicks, key presses, input events | Browser |
| Networking | `XMLHttpRequest` load events, WebSocket messages | Browser |
| Messaging | `postMessage`, `MessageChannel`, Worker messages | Both |
| I/O completion | `fs.readFile` callbacks, socket data | Node.js |
| `setImmediate` | Check-phase callbacks | Node.js |
The pattern is always the same. Your code calls an API, the host does the work outside the engine, and when the work completes the host queues a task that will call your callback.
First In, First Out Within a Source
Tasks from the same source run in the order they were queued. Three zero-delay timers scheduled one after another run in that order:
setTimeout(() => console.log('timer 1'), 0);
setTimeout(() => console.log('timer 2'), 0);
setTimeout(() => console.log('timer 3'), 0);
// Output: timer 1, timer 2, timer 3The task's place in line depends on when it enters the queue, not on when you called the API. A timer joins the queue only when it expires, so a short timer scheduled later still runs before a longer timer scheduled earlier:
setTimeout(() => console.log('slow (10 ms)'), 10);
setTimeout(() => console.log('fast (0 ms)'), 0);
// Output: fast (0 ms), slow (10 ms)Tasks Queued During a Task Wait Their Turn
A running task can schedule new tasks, and this is where intuition often breaks. A new task goes to the back of the queue. It does not run inside the current task, and it does not jump ahead of tasks that are already waiting.
setTimeout(() => {
console.log('task A starts');
setTimeout(() => console.log('task C (queued by A)'), 0);
console.log('task A ends');
}, 0);
setTimeout(() => console.log('task B'), 0);
// Output:
// task A starts
// task A ends
// task B
// task C (queued by A)The trace goes like this. The script task queues A and B. When the script finishes, A runs, queues C behind B, and runs to completion. B runs next, then C. Each line in task A prints before anything else because of run-to-completion: nothing interrupts A once it has started.
There Is More Than One Task Queue
The simple model of "one task queue" is good enough for most reasoning, but it is not exactly what browsers do. The HTML specification lets a browser keep several task queues, usually one per task source. On each turn the browser picks one queue and takes its oldest task. The specification guarantees FIFO order inside a single source. It does not fix the order between sources.
Browsers use this freedom to stay responsive. For example, a browser can give user-input tasks priority over timer tasks so that clicks feel quick even while many timers are firing.
In practice, you can rely on ordering only within one source. Two tasks from different sources have no guaranteed order:
const channel = new MessageChannel();
channel.port1.onmessage = () => {
console.log('message task');
channel.port1.close();
};
setTimeout(() => console.log('timer task'), 0);
channel.port2.postMessage(null);
// The order of these two lines is not guaranteed.
// Most environments print "message task" first, but do not depend on it.This code runs in browsers and in Node.js 15 or later, where MessageChannel is a global. Closing the port lets Node.js exit once the message has been handled.
Node.js takes the multi-queue idea further. It keeps separate queues for timers, I/O callbacks, and setImmediate callbacks, and it visits them in a fixed sequence of phases. A later chapter covers those phases. For now, the browser rule carries over: within one queue, tasks run first in, first out.
Common Errors
Assuming every event handler is a task
A real user click arrives as a task. A click you trigger from code does not. Calling element.click() or dispatchEvent() runs the listeners synchronously, inside the current task:
// Run in a browser console
const button = document.createElement('button');
button.addEventListener('click', () => console.log('click handler'));
console.log('before');
button.click();
console.log('after');
// Output: before, click handler, afterThe handler behaves like a plain function call here. This difference can change how your code behaves in tests that simulate clicks.
Thinking a long queue runs "in parallel"
A hundred queued tasks still run one after another on the single thread. A queue holds work that is waiting. It does not run that work faster.
Expecting a task to run while code is still executing
A task never starts while the call stack has frames on it. If the current task runs a long loop, every queued task waits, including the one that would handle the user's click. A later chapter on blocking the loop covers this in detail.
Treating the queue as a priority system you control
Standard APIs give you no way to push a task to the front of the queue. If you need work to run before the next task, use a microtask instead. The microtask chapter covers when that is appropriate.
Summary
- A task is a callback that the host schedules to run later, starting on an empty call stack and running to completion.
- The script itself, timers, user input, networking, messaging, and I/O all produce tasks.
- Within one task source, tasks run in the order they entered the queue. A timer enters the queue when it expires, not when you schedule it.
- Tasks queued by a running task go to the back of the line.
- Browsers can keep several task queues and choose between them, so the order between different sources is not guaranteed.
The next chapter covers how the event loop decides when to take the next task and what else it does on each turn.
Exercise
Predict the output of this code and explain each step. setTimeout(() => console.log('X'), 5); setTimeout(() => { console.log('Y'); setTimeout(() => console.log('Z'), 0); }, 0); console.log('W');
Show answer
W, Y, Z, X in practice. W prints first because the script task runs to completion before any other task. The 0 ms timer expires first, so Y's task runs and queues Z. Z's timer expires almost immediately, while X still has about 5 ms left, so Z usually runs before X. The guaranteed part is that W comes first and Y comes before Z. The order of Z and X depends on timing, because each timer joins the queue when it expires.
Exercise
A test calls button.click() and then checks that a counter was incremented by the click handler. A colleague says the check should be wrapped in setTimeout to "wait for the click task." Are they right?
Show answer
No. Calling element.click() runs the listeners synchronously in the current task, so the counter is already updated on the next line. Only real user clicks arrive as tasks. Wrapping the check in setTimeout adds a delay the test does not need.
Exercise
Why can't you rely on a setTimeout(fn, 0) callback running before a MessageChannel message posted right after it?
Show answer
They come from different task sources. Browsers may keep a separate queue for each source and choose which queue to serve on each turn. FIFO order is guaranteed only within a single source, so the order between a timer task and a message task is not defined.