A timer lets browser JavaScript defer code until later. For expensive work, scheduling smaller chunks can give the browser room to respond instead of leaving the interface unresponsive. section 13.2.2
Listing 13.5. Using a timer to break up a long-running task
const rowCount = 20000; #A
const divideInto = 4;
const chunkSize = rowCount/divideInto;
let iteration = 0;
const table = document.getElementsByTagName("tbody")[0];
setTimeout(function generateRows(){
const base = chunkSize * iteration; #B
for (let i = 0; i < chunkSize; i++) {
const tr = document.createElement("tr");
for (let t = 0; t < 6; t++) {
const td = document.createElement("td");
td.appendChild(
document.createTextNode((i + base) + "," + t +
"," + iteration));
tr.appendChild(td);
}
table.appendChild(tr);
}
iteration++;
if (iteration < divideInto) #C
setTimeout(generateRows, 0); #C
},0); #D
This example builds a 20,000-row table in four chunks, scheduling each next chunk with setTimeout(generateRows, 0). section 13.2.2
For a long-running DOM task:
- Divide the work into smaller batches, track which batch comes next, and schedule another batch only while work remains. section 13.2.2
- Use chunking to reduce how long one operation occupies the browser; it makes work less likely to interrupt normal interaction. section 13.2.2



