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

