liveBook · Manning

Timer delay

As explained in Secrets of the JavaScript Ninja, Second Edition

The minimum elapsed time requested before a timer's corresponding task is added to the task queue, not a guarantee of when it executes.

A timer delay is the minimum elapsed time requested before its matching task is added to the task queue—not a promise that the handler will run then. If JavaScript is already running, it must finish first; the timer task waits its turn. section 13.2.1

A 10 ms delay in a busy event loop

A 10 ms timeout expires while an 18 ms mainline task is still running. Its handler is queued, then waits for that task to finish before it can execute. section 13.2.1

Listing 13.3. Pseudocode for our time-out and interval demo
<button id="myButton"></button>
<script>
  setTimeout(function timeoutHandler(){                             #A
    /*Some timeout handle code that runs for 6ms*/                  #A
  }, 10);                                                           #A

  setInterval(function intervalHandler(){                           #B
    /*Some interval handle code that runs for 8ms*/                 #B
  }, 10);                                                           #B

  const myButton = document.getElementById("myButton");      
  myButton.addEventListener("click", function clickHandler(){       #C
     /*Some click handle code that runs for 10ms*/                  #C
  });                                                               #C

  /*Code that runs for 18ms*/
</script>

Compare the 10 ms timeout and interval with the click handler and running mainline code. section 13.2.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Traces timer expiry into task-queue insertion and explains why queued work waits for running task completion.
Examples
Uses 10 ms timeout and interval timers alongside an 18 ms mainline task and a button click.
What you can do after
Understand why a requested timer delay does not guarantee immediate handler execution.
How it connects
Connects timer delay to the event loop, task queue, setTimeout, and setInterval.

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.