Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to run code repeatedly at an interval

Short answer

setInterval() calls a function again and again with the given pause. clearInterval() stops it:

let count = 0;
const timer = setInterval(() => {
  count++;
  console.log('tick', count);
  if (count === 3) clearInterval(timer);
}, 200);

Output:

tick 1
tick 2
tick 3

A countdown

The same approach counts down and stops at zero:

let seconds = 3;
const timer = setInterval(() => {
  console.log(seconds > 0 ? seconds : 'Start!');
  if (seconds === 0) clearInterval(timer);
  seconds--;
}, 100);

Output:

3
2
1
Start!

A chain of setTimeout

For requests it is better to plan the next call only after the previous one has finished. Then calls never overlap:

async function poll() {
  const response = await fetch('/api/status');
  showStatus(await response.json());
  setTimeout(poll, 5000);
}
 
poll();

Common mistake

Without clearInterval() the interval runs forever, even when it is no longer needed. Always save the id to be able to stop it:

const timer = setInterval(() => {}, 1000);
clearInterval(timer);
 
console.log('interval stopped');

Output:

interval stopped

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.