A long-running JavaScript task can make a browser unresponsive. Split it into smaller chunks and schedule each chunk with a timer, giving the browser opportunities to handle other work between them. 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 creates table rows in four timer-scheduled chunks, tracking progress with an iteration counter and base offset. section 13.2.2
