Cutting a timeline coordinates parallel work by drawing a boundary across timelines. Actions before the cut finish before actions after it begin, while independent work may finish in any order. section 17.9
The cut lets asynchronous callbacks wait for one another before using their combined result. This prevents a race condition and makes the system easier to analyze by separating parallel preparation from sequential continuation. section 17.10 section 2.18
Use cutting when:
- Multiple AJAX responses must all arrive before updating the DOM. section 17.9
- Several independent preparations can run in parallel, but assembly must happen in sequence. section 2.18
- You need to reduce the possible orderings enough to inspect behavior and avoid timing-dependent results. section 17.14
Waiting for three timelines
Cut(3, callback) returns a shared done function. Each timeline calls done when finished; the third call runs the callback, producing “3 timelines are finished.” 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 compact JavaScript primitive that counts completed timelines and invokes its callback only after the required number has finished. section 17.10
