setInterval
Runs a function again and again at an interval.
Available since: Web API
Syntax
setInterval(callback, delay, ...args)Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | Function | The function to run repeatedly. |
| delay | number | The interval in milliseconds. |
| ...args | any | Optional. 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
- clearInterval — Stops a repeating setInterval.
- setTimeout — Runs a function once after a delay.
Related recipes
In the tutorial
- Timers — The setTimeout and setInterval functions in JavaScript: delayed and repeated calls, arguments, cancelling a timer.