liveBook · Manning

Event loop

As explained in Secrets of the JavaScript Ninja, Third Edition

An event loop is a mechanism that repeatedly processes queued tasks and callbacks to support asynchronous, event-driven execution.

JavaScript runs one piece of code at a time: events wait in queues rather than interrupting execution. When the current code finishes, the event loop processes queued work. section 8.1.4

Callback timing depends on which queue holds the work:

  • Promise callbacks run asynchronously, even when the promise is already settled. section 8.1.4
  • Promise callbacks use the microtask queue; setTimeout callbacks use the task, or macrotask, queue. Microtasks take priority over macrotasks. section 8.1.4
  • setTimeout(callback, 0) does not mean immediate execution; the HTML Living Standard specifies a minimum delay of 4 milliseconds. section 8.1.4
Listing 8.6 Queueing callbacks with setTimeout and then
setTimeout(() => {
  console.log("setTimeout callback");
}, 0);
 
Promise.resolve(true).then(() => {
  console.log("then callback");
});
 
console.log("end of script");

In this example, the script logs first, the promise's then callback follows, and the setTimeout callback runs last. section 8.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines single-threaded queue processing and distinguishes prioritized microtasks from task-queue callbacks.
Examples
Contrasts end-of-script logging with a promise callback and a setTimeout callback.
What you can do after
Evaluate asynchronous callback order by comparing promise microtasks with setTimeout tasks.
How it connects
Connects callback scheduling with promises, setTimeout, microtasks, and task queues.

Also explained in

Compare how 14 books explain event loop →

Related concepts

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