CodeBlanks Logo Icon CodeBlanks

Stopping with clearInterval

JavaScript course · Intermediate · Lesson 62/134

Learn to stop a timer with clearInterval and clearTimeout.

Stopping a timer with its id

Both setInterval and setTimeout return an id. You store this id in a variable and stop the timer with clearInterval(id) or clearTimeout(id).

const id = setInterval(() => {
  console.log('Tick');
}, 1000);
clearInterval(id);

Here id holds the id returned by setInterval. When clearInterval(id) is called, the repeating timer stops right away. In the same way, clearTimeout(id) cancels a setTimeout that has not run yet.

Stopping on a condition

To stop a timer on a condition, you write an if inside the callback. When the condition is met, clearInterval is called and the repeats end.

let count = 0;
const id = setInterval(() => {
  count = count + 1;
  if (count >= 3) {
    clearInterval(id);
  }
}, 1000);

This code stops the timer once count reaches 3. The id variable is reachable from inside the callback because it is declared in the same scope. This way the counter stops where you want, not forever.

Exercise Stop the counter when it passes 3

Complete the setInterval below: when count is greater than 3, stop it with clearInterval(id).

Show example solution
const counter = document.querySelector('#counter');
let count = 0;
const id = setInterval(() => {
  count = count + 1;
  counter.textContent = count;
  if (count > 3) {
    clearInterval(id);
  }
}, 1000);

Test yourself

  1. Which stops a setInterval?

    const id = setInterval(() => {
      console.log('Tick');
    }, 1000);
    • stopInterval(id)
    • pauseTimer(id)
    • clearInterval(id)
    • endInterval(id)
    Show answer

    clearInterval(id) — Correct! clearInterval(id) stops the repeating timer.

  2. Complete the clearInterval call

    const id = setInterval(() => {
      console.log('Tick');
    }, 1000);
    ____(id);
    Show answer
    const id = setInterval(() => {
      console.log('Tick');
    }, 1000);
    clearInterval(id);
  3. Match functions to their purpose

    setInterval
    starts a repeating timer
    clearInterval
    stops a repeating timer
    setTimeout
    starts a one-shot timer
    clearTimeout
    cancels a timer not yet fired

All lessons in Intermediate