liveBook · Manning

setInterval

As explained in Secrets of the JavaScript Ninja, Second Edition

A timer function that repeatedly schedules a callback at a specified interval until canceled.

setInterval repeatedly schedules a callback until it is explicitly cleared. Its delay is not a promise of exact execution time: JavaScript tasks can postpone callbacks, and a new interval firing is dropped when that interval already has a task waiting in the queue. 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>

See the interval callback alongside a timeout, a click handler, and long-running mainline code in the scheduling example. section 13.2.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Traces interval firings through the task queue and explains dropped firings, but does not detail timer setup or cancellation.
Examples
Uses a 10 ms interval beside a timeout, click handler, and 18 ms mainline task.
What you can do after
Understand why interval callbacks may run late or have firings dropped while a task is already queued.
How it connects
Relates setInterval to setTimeout, the event loop, and the task queue.

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.