liveBook · Manning

Event loop

As explained in Secrets of the JavaScript Ninja, Second Edition

A runtime scheduling mechanism that coordinates when queued events and callbacks are handled by an application.

A click can happen while JavaScript is busy, but its handler cannot interrupt the code already running. The event loop coordinates the browser’s work so an application can respond to events without running two JavaScript handlers at once. section 2.3.3

Start with a simple model: the browser queues events as they occur. The event loop takes an event, runs its handler to completion, then checks for the next one. If a mousemove event arrives before a click, the click waits while the mousemove handler runs. Once the queue is empty, the loop waits for more work. section 2.3.3

Two events, two DOM updates

A mousemove handler appends a list item reading “Event: mousemove.” Only after that handler finishes does the click handler run and append another item. The resulting DOM reflects two completed handlers, not two handlers executing simultaneously. section 2.3.3

The fuller model has at least two queues. Macrotasks are discrete units of work such as parsing HTML, running mainline JavaScript, handling input, or handling timers. After a macrotask, the browser may do other work, including re-rendering the page. Microtasks, including promise callbacks and DOM mutation changes, update application state before the browser moves on to work such as re-rendering. Implementations may maintain several queues of each kind. section 13.1

Figure 13.1. The event loop usually has access to at least two task queues: a microtask queue and a macrotask queue. Both types of tasks are handled one at a time.

The two-queue diagram helps replace the useful but incomplete picture of one event queue; both kinds of task are handled one at a time. section 13.1

Why a 10 ms timer runs later

Suppose mainline JavaScript runs for 18 ms while a click, a 10 ms timeout, and a 10 ms interval become ready. Their handlers must wait in the task queue. The click handler starts when the initial code finishes and runs for 10 ms, so the timeout handler does not start until about 28 ms. A further interval firing is dropped if a task for that same interval is already waiting. A timer delay therefore does not promise an exact handler start time. section 13.2.1

Listing 13.3. Pseudocode for our time-out and interval demo
<button id="myButton"></button>
<script>
  setTimeout(function timeoutHandler(){                             #A
    /*Some timeout handle code that runs for 6ms*/                  #A
  }, 10);                                                           #A

  setInterval(function intervalHandler(){                           #B
    /*Some interval handle code that runs for 8ms*/                 #B
  }, 10);                                                           #B

  const myButton = document.getElementById("myButton");      
  myButton.addEventListener("click", function clickHandler(){       #C
     /*Some click handle code that runs for 10ms*/                  #C
  });                                                               #C

  /*Code that runs for 18ms*/
</script>

The pseudocode supplies the timeout, interval, click handler, and 18 ms initial block used in the timing example. section 13.2.1

Keep these distinctions in mind:

  • An event occurring is not the same as its handler starting; currently running code must finish first. section 2.3.3
  • A timer expiring places work in a queue; other queued work can delay its handler. section 13.2.1
  • The event loop belongs to the browser’s HTML-defined behavior, rather than being specified as an ECMAScript event loop; other environments, including Node.js, also use event loops. section 13.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Builds from a single event queue to macrotask and microtask queues, then works through delayed timer execution.
Examples
Traces mousemove and click DOM updates and a queued click, timeout, and interval timing scenario.
What it assumes
Assumes familiarity with JavaScript handlers and browser pages while teaching the queue model from a simple event sequence.
What you can do after
Diagnose/debug why an event or timer handler waits despite its event occurring or its delay expiring.
How it connects
Links event handlers, the DOM, promises, rendering, and timers through browser task scheduling.

Also explained in

Compare how 11 books explain event loop →

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.