liveBook · Manning

Single-threaded execution model

As explained in Grokking Simplicity

A single-threaded runtime is an execution environment in which program actions execute on one thread at a time.

A single-threaded runtime executes one action at a time on one thread. Each job runs to completion before the event loop starts another, so jobs do not interleave. section 15.15 section 15.18

In browser JavaScript, clicks, typing, and AJAX events place callbacks and event data on the job queue. The event loop repeatedly removes one job and executes its callback. section 15.15

Use the model to simplify execution timelines:

  • Consolidate actions on one timeline because a running timeline cannot be interrupted by another thread. section 15.18
  • Keep asynchronous continuations in separate boxes when their timing can vary; the model reduces uncertainty but does not remove it. section 15.21
  • Reduce timelines, shorten them, eliminate shared resources, or coordinate shared access with promises and other concurrency primitives. section 17.17

Synchronous work and asynchronous callbacks

The actions in dinner(food)—cook, serve, and eat—can be treated as one uninterrupted timeline when synchronous. In add-to-cart code, callback chains can be combined into a shorter timeline, but asynchronous boundaries remain separate. A Cut primitive can safely count completed timelines using a synchronously accessed variable, then invoke a callback when all have finished. section 15.18 section 15.20 section 17.10

function Cut(num, callback) { #1 
    var num_finished = 0; #2
    return function() {
        num_finished += 1; #3
        if(num_finished === num)
            callback(); #4
    };
}

Inspect the Cut implementation that counts completed timelines and calls a callback after the final completion. section 17.10

How Grokking Simplicity covers it

How deep it goes
Defines event-loop execution, simplifies timeline diagrams, and implements coordination, but does not eliminate asynchronous ordering problems.
Examples
Uses dinner actions, browser events, add-to-cart callbacks, timeline diagrams, and a Cut completion counter.
What you can do after
Diagnose asynchronous ordering issues and coordinate shared work using JavaScript’s sequential callback execution.
How it connects
Connects event loops, job queues, callbacks, asynchronous programming, race conditions, and concurrency primitives.

Also explained in

Compare how 2 books explain single-threaded execution model →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.