JavaScript Timing Methods

Instead of executing a function immediately, it is sometimes useful to JavaScript wait a period before executing a function, or to have JavaScript repeatedly execute a function at set intervals. JavaScript two such methods setTimeout() and setInterval().

setTimeout

The setTimeout() method will execute a function after a specified time has passed. The method can take two arguments, the function to be executed and the length of time, in milliseconds, to wait.

The setTimeout() method can be used any time delayed execution or create a timed sequence of events.

const $button = document.getElementById('button')
const $stage = document.getElementById('stage')

$button.addEventListener('click', function () {
  $stage.innerHTML = '<p>Abra cadabra...</p>'
  
  setTimeout(function () {
    $stage.innerHTML += '<p>...</p>'
  }, 1000)
  
  setTimeout(function () {
    $stage.innerHTML += '<h1><em>Tada!</em></h1>'
  }, 2000)
})

setInterval

The setInterval() method will repeatedly call a function with fixed delays between each call. Similar to setTimeout(), the setInterval() method takes a function and a time delay in milliseconds.

The clearInterval() method is used to stop the setInterval() method. It will take a single argument, which is the timer id, which is returned by the setInterval() method.

The setInterval() method can be used anytime the page needs to be updated periodically.

const $timer = document.getElementById('timer')
const $start = document.getElementById('start')
const $stop = document.getElementById('stop')

let id = 0

$start.addEventListener('click', function () {
   let timer = 0
   $timer.textContent = 0
   id = setInterval(function () {
     timer++
     $timer.textContent = timer
   }, 1000)
})

$stop.addEventListener('click', function () {
  clearInterval(id)
})