liveBook · Manning

Timer

As explained in Secrets of the JavaScript Ninja, Second Edition

A host-environment scheduling mechanism for running code after a delay or at repeated intervals.

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

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Demonstrates chunk size, iteration tracking, and recursive setTimeout scheduling in a worked DOM example.
Examples
Uses a 20,000-row table with six cells per row, first built synchronously and then in four timer-scheduled chunks.
What you can do after
Apply setTimeout to divide long-running DOM work into batches that are less likely to block interaction.
How it connects
Connects timers with events, the DOM, and the event loop.

Also explained in

Compare how 4 books explain timer →

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.