Interleaving is an ordering formed by combining steps from multiple timelines while preserving each timeline’s internal order. An action from one timeline may occur between two actions from another when the execution model permits it. section 15.11
Use timeline diagrams to make possible orderings visible:
- Place actions that may run simultaneously or out of order on separate timelines. section 15.22
- Use dotted lines for required ordering, such as an asynchronous callback following its request. section 15.22
- Combine actions that cannot interleave into one box, and consolidate a timeline that starts another. section 15.22 section 15.20
Two clicks, different answers
Two click-handler timelines can produce ten possible orderings. Slow clicks may produce the correct result, while a fast interleaving can produce the wrong value because the actions occur in a different order. Tracing one problematic ordering exposes the bug, but longer timelines can create too many orderings to inspect manually. section 15.24 section 15.25
Inspect the click-handler timeline to follow a concrete ordering and see how interleaving changes the resulting variable values. section 15.25
The execution model determines how much interleaving is possible. JavaScript’s synchronous actions do not interleave on its single main thread, but asynchronous callbacks run later at an unknown time and reintroduce separate timeline boxes. Multithreaded systems allow broader interleaving, while message-passing processes avoid shared memory. section 15.14 section 15.8
