setInterval
Repeatedly calls a function with a fixed time delay between each call
Syntax
setInterval(callback, delay?, ...args)Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | Function | A function to be executed every delay milliseconds |
| delay | number | Time in milliseconds between each execution |
| args | any[] | Additional arguments passed to the callback |
Return Value
A positive integer ID that identifies the interval (use with clearInterval to cancel)
Examples
let count = 0;
const id = setInterval(() => {
count++;
console.log(`Tick ${count}`);
if (count >= 5) clearInterval(id);
}, 1000);function poll(url: string, intervalMs: number) {
const id = setInterval(async () => {
const res = await fetch(url);
const data = await res.json();
if (data.complete) clearInterval(id);
}, intervalMs);
return id;
}const clock = setInterval(() => {
console.log(new Date().toLocaleTimeString());
}, 1000);Understanding setInterval
The setInterval method in JavaScript repeatedly calls a function with a fixed time delay between each call. It belongs to the window object and is one of the most widely used methods for working with window values in modern JavaScript and TypeScript applications.
The method signature is setInterval(callback, delay?, ...args). It accepts 3 parameters: callback, delay, args. When called, it returns a positive integer id that identifies the interval (use with clearinterval to cancel). Understanding when and how to use setInterval() helps you write more expressive, readable code.
Common use cases for setInterval include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like window-clearinterval, window-settimeout, window-cleartimeout, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for setInterval is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
More Global / Window Methods
Other methods in the Global / Window object
Related Tools
More Global / Window Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.