Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

setInterval

Runs a function again and again at an interval.

Available since: Web API

Syntax

setInterval(callback, delay, ...args)

Parameters

ParameterTypeDescription
callbackFunctionThe function to run repeatedly.
delaynumberThe interval in milliseconds.
...argsanyOptional. Arguments for the function.

Return value

numberThe timer id — for stopping with clearInterval.

Examples

A countdown:

let count = 3;
 
const id = setInterval(() => {
  console.log(count);
  count--;
  if (count === 0) {
    clearInterval(id);
    console.log('Go!');
  }
}, 200);

Output:

3
2
1
Go!

Notes

An interval runs until it is stopped with clearInterval(). Do not forget to stop it, or the function is called forever.

See also

Related recipes

In the tutorial

  • Timers — The setTimeout and setInterval functions in JavaScript: delayed and repeated calls, arguments, cancelling a timer.

Thanks for reading!

Donate to the site — we work hard for you.