liveBook · Manning

Event loop

As explained in The Joy of JavaScript

An event loop is a runtime scheduling mechanism that repeatedly dequeues and executes pending callbacks or tasks to drive asynchronous execution.

The event loop is part of JavaScript’s runtime scheduling architecture. It works with a callback queue to run pending asynchronous work while the main thread continues. This gives a single-threaded JavaScript program a way to handle events and delayed results without writing every operation as a blocking sequence. section 1.5 section 8.0

Callbacks and promises both use this architecture. A mouse event or HTTP request can provide a callback; a promise instead gives the eventual result a consistent API. With `doSomething().then(doSomethingElse)`, `then` marks what should happen after the first operation produces its result. `async`/`await` makes that flow look linear, but still relies on promises and the event loop. section 8.2 section 1.5

Reading a file without a synchronous call

Compare `fs.readFileSync('blocks.txt')` with `fs.readFile('blocks.txt', callback)` or `fs.promises.readFile('blocks.txt').then(handleData)`. The latter two express work whose result arrives later; the promise form separates the eventual value from the function that handles it. section 8.2

Scheduling also matters during module loading. If a module uses top-level `await`, a module that imports it must wait for it to finish. Other sibling dependencies can continue loading, so the wait need not stop unrelated work. section 8.6

Figure 8.2 A simplified view of how the Node.js architecture handles asynchronous tasks. The event loop time slices these tasks so that code never blocks, providing the illusion of concurrency.

A simplified Node.js diagram illustrates how the event loop interleaves asynchronous tasks with continuing code. section 8.2

How The Joy of JavaScript covers it

How deep it goes
Explains the callback queue and interleaved scheduling at a high level, without detailing queue rules or engine internals.
Examples
Contrasts synchronous, callback-based, and promise-based Node.js file reads and considers a module using top-level await.
What it assumes
Assumes familiarity with callbacks; introduces the task queue and event loop only as a high-level architecture.
What you can do after
Evaluate/understand how asynchronous work can proceed alongside main code and why dependent modules wait at top-level await.
How it connects
Connects the event loop to callbacks, promises, async/await, HTTP requests, and top-level await.

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 The Joy of JavaScript. The section links point to the parts of the book it draws on.