Timers

setTimeout and setInterval

Example

setTimeout runs a function once after a delay (ms); setInterval runs it repeatedly until cleared:

console.log("start");
setTimeout(() => console.log("after 100 ms"), 100);

let ticks = 0;
const id = setInterval(() => {
  ticks++;
  console.log("tick", ticks);
  if (ticks === 3) clearInterval(id);
}, 30);
console.log("end of script");

Output

start
end of script
tick 1
tick 2
after 100 ms
tick 3

A Countdown in the Page

Example

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<p>Offer ends in <b id="t">5</b> seconds</p>
<script>
  let left = 5;
  const el = document.getElementById("t");
  const timer = setInterval(() => {
    left--;
    el.textContent = left;
    if (left === 0) {
      clearInterval(timer);
      el.parentElement.textContent = "Offer expired!";
    }
  }, 1000);
</script>

</body>
</html>

Result

Note: The delay is a minimum, not a guarantee: the callback waits until the call stack is free (see the Event Loop).