liveBook · Manning

Non-blocking call

As explained in Secrets of the JavaScript Ninja, Second Edition

An operation arranged so that its work does not block the program’s execution while it is being performed.

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

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains timer-based chunking, iteration offsets, and scheduling subsequent chunks.
Examples
Creates 20,000 table rows with six cells each, dividing the work into four timer-scheduled chunks.
What you can do after
Apply timer-based chunking with setTimeout to divide expensive DOM work into smaller tasks.
How it connects
Connects timers and the event loop with DOM manipulation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.