Glossary / Task queue

Task queue

A task queue holds units of host-scheduled work that an event loop can run when the current JavaScript job and higher-priority work allow it. In browser terminology, tasks (often informally called macrotasks) include timer callbacks, user events, and message events. The phrase “task queue” is an oversimplification: HTML defines task sources and event loops, and hosts need not merge every source into one strict global FIFO.

Ordering and yielding

A task runs to completion. After it ends, browsers generally perform a microtask checkpoint before selecting another task; rendering may occur at an appropriate point. A zero-delay timeout schedules a future task—it does not run immediately or necessarily before paint. Browser throttling, current work, background tabs, and other task sources affect actual timing.

setTimeout(() => console.log("task"), 0);
queueMicrotask(() => console.log("microtask"));
console.log("current job");
// current job, microtask, task

Task boundaries are useful when yielding so the browser can process input/rendering. setTimeout(fn, 0) is one way to schedule a later task, though timers are throttled and not precise. scheduler.postTask has evolving support and priority semantics; check targets before relying on it. Repeated microtasks do not yield to tasks.

Interview questions

  1. Does setTimeout with zero run immediately? No; it queues a callback for a later opportunity.
  2. What usually runs before the next task after a task completes? The microtask queue is drained.
  3. Are all browser tasks in one simple FIFO? No; HTML has task sources and scheduling choices.
  4. Why yield to a task instead of a microtask? A task boundary can let input and rendering progress; microtasks drain before that.

References