setInterval() / clearInterval()
Repeatedly executes a function at a specified time interval. Use clearInterval() to stop the repetition.
Syntax
// Repeatedly calls a function at a fixed interval. var timerID = setInterval(function, milliseconds); // Stops the repetition. clearInterval(timerID);
Arguments
| Argument | Description |
|---|---|
| function | Specifies the callback function to execute repeatedly. |
| milliseconds | Specifies the interval in milliseconds. 1000 milliseconds equals 1 second. |
Return Value
Returns a numeric ID that identifies the timer. Pass this ID to clearInterval() to stop the repetition.
Sample Code
// Example: count up every second
var count = 0;
var timerID = setInterval(function() {
count++;
console.log("Count: " + count);
if (count >= 5) {
clearInterval(timerID); // Stop after 5 iterations.
console.log("Timer stopped");
}
}, 1000);
// Smooth animation using requestAnimationFrame()
var position = 0;
var box = document.querySelector("#box");
function animate() {
position += 2;
box.style.left = position + "px"; // Move 2px to the right each frame.
if (position < 300) {
requestAnimationFrame(animate); // Run again on the next frame.
}
}
requestAnimationFrame(animate);
Difference Between setInterval() and requestAnimationFrame()
| Method | Description |
|---|---|
| setInterval() | Repeats a process at a fixed time interval. Well suited for tasks that run on a regular schedule, such as countdown timers or periodic data fetching. |
| requestAnimationFrame() | Executes a process in sync with the browser's rendering cycle. Typically called 60 times per second, making it ideal for smooth animations. It automatically pauses when the tab is hidden, which is better for performance. |
Overview
setInterval() is a timer function that repeatedly calls a function at a specified millisecond interval. It is commonly used for countdown timers, periodic data updates, and automatic slideshow transitions.
Unless you call clearInterval(), the function runs forever — always include a condition to stop it. Even after leaving the page, the timer may keep running internally and cause memory leaks.
For animations, requestAnimationFrame() is recommended over setInterval(). Because requestAnimationFrame() syncs with the browser's rendering timing, it produces smooth 60 fps animations and automatically pauses when the tab is hidden. To run a delayed function only once, use setTimeout().
Browser Compatibility
3 or earlier ×
3 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.