liveBook · Manning

Macrotask

As explained in Secrets of the JavaScript Ninja, Second Edition

An event-loop task such as an event handler or timer callback, processed separately from microtasks.

A click handler may finish while another click is already waiting. The waiting handler does not interrupt the first: each macrotask is a discrete unit of work that runs on its own turn of the event loop. Macrotasks are also called tasks. section 13.1 section 13.4

What counts as a macrotask?

  • Running mainline JavaScript, creating the main document object, and parsing HTML. section 13.1
  • Handling page-load, input, network, or timer events, and changing the current URL. section 13.1

The distinction matters when a macrotask queues a microtask. Promise callbacks are microtasks: after the current task finishes, the event loop processes the microtask queue before moving to another macrotask or allowing a re-render. A queued microtask can therefore run ahead of an older, waiting click event. section 13.1 section 13.1.2

Two clicks and a resolved promise

A first click handler calls Promise.resolve().then(...) and keeps running. Meanwhile, a second click waits as a macrotask. Once the first handler ends, the promise callback runs before the second click handler—even if that click was queued earlier. The promise callback does not interrupt the handler that created it. section 13.1.2

Figure 13.9. A page can be re-rendered between two macrotasks (mainline JavaScript execution and first click handler), while it can’t be rendered before a microtask is executed (before the promise handler).

The timing diagram distinguishes a possible re-render between macrotasks from the interval before a queued promise microtask, when re-rendering cannot yet occur. section 13.1.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines macrotasks, identifies browser examples, and works through queue ordering and rendering; does not detail browser-specific queue implementations.
Examples
Uses two click handlers and a resolved promise to show a microtask overtaking a waiting click macrotask.
What it assumes
Assumes familiarity with JavaScript event handlers and promises while defining task categories and their queue behavior.
What you can do after
Diagnose/debug with it when click handlers, promise callbacks, and rendering occur in an unexpected order.
How it connects
Connects macrotasks to the event loop, microtasks, promises, event handlers, timers, and UI rendering.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.