agyanadda@gmail.com

JS Timers

Working with the Page 1 min read Updated Dec 1, 2026 Topic 29 of 38

Timers run code later or repeatedly.

setTimeout — run once after a delay

setTimeout(() => alert('3 seconds passed'), 3000);

Time is in milliseconds (1000 ms = 1 second).

setInterval — run again and again

const id = setInterval(() => console.log('tick'), 1000);

Stop a timer

Both return an id. Pass it to clearTimeout(id) or clearInterval(id).

Uses

Countdowns, clocks, slideshows, auto-saving, hiding a message after a few seconds.

Example

Example — Countdown timer HTML
<h1 id="time">10</h1>
<button id="start">Start</button>
<button id="stop">Stop</button>

<script>
  let seconds = 10;
  let timer = null;
  const show = () => document.getElementById('time').textContent = seconds;

  document.getElementById('start').onclick = () => {
    if (timer) return;
    timer = setInterval(() => {
      seconds--;
      show();
      if (seconds === 0) {
        clearInterval(timer);
        timer = null;
        document.getElementById('time').textContent = 'Time up!';
      }
    }, 1000);
  };

  document.getElementById('stop').onclick = () => {
    clearInterval(timer);
    timer = null;
  };
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function runs code repeatedly?

Exercise 2 Fill in the Blank

2 seconds is ___ milliseconds.

Exercise 3 True / False

clearInterval stops a timer created by setInterval.

Frequently Asked Questions

No. It runs after the current code finishes, so it is a little later — it is used to wait for the next moment.