The setInterval() method runs a function on a repeating timer. This tutorial covers syntax, interval IDs, delay in milliseconds, passing arguments, stopping with clearInterval(), comparison with setTimeout(), five examples, and cleanup habits.
01
Syntax
setInterval(fn, ms)
02
Repeats
Until cleared
03
ID
Save return value
04
Stop
clearInterval(id)
05
vs timeout
Once vs loop
06
Args
Extra parameters
Fundamentals
Introduction
Many features need code to run again and again: live clocks, countdown timers, slideshows, and polling for new messages. JavaScript timers handle this without blocking the page. The setInterval() method schedules a callback on the browser’s event loop so your UI stays responsive between ticks.
Each call returns an interval ID. Keep that ID so you can stop the loop with clearInterval() when the user clicks Stop or navigates away. Forgetting to clear intervals is a common source of bugs and wasted battery life.
Concept
Understanding the setInterval() Method
setInterval(callback, delayMs, arg1, arg2, ...) registers callback to run every delayMs milliseconds (minimum ~4ms in modern browsers, but use sensible values like 1000 for a one-second clock). It returns a numeric ID immediately—the first run happens after the delay, not instantly.
Timers are asynchronous: code after setInterval() runs right away while the callback waits for the clock. Multiple intervals can run at the same time; each has its own ID.
💡
Beginner Tip
Always assign the return value: const id = setInterval(tick, 1000). Without the ID you cannot stop that specific timer with clearInterval(id).
Foundation
📝 Syntax
General form of setInterval():
JavaScript
const intervalId = setInterval(callback, delayMs, param1, param2);
// shorthand (same in browsers):
const id = setInterval(tick, 1000);
Parameters
callback — function to execute on each tick. Can be a function reference or inline function.
delayMs — milliseconds between calls. Use 1000 for one second.
param1, param2, ... (optional) — extra values passed to callback.
Return value
A numeric interval ID. Pass it to clearInterval() to cancel.
The callback runs repeatedly until you call clearInterval(intervalId) or leave the page. The first execution waits 2000ms.
📈 Practical Patterns
Clocks, counters, arguments, and bounded loops.
Example 2 — Update a Live Clock Every Second
Refresh DOM text with the current time.
JavaScript
function updateClock() {
const now = new Date().toLocaleTimeString();
document.getElementById("clock").textContent = now;
}
updateClock(); // show immediately
setInterval(updateClock, 1000);
Start → count increases every 500ms
Stop → counter freezes
Start again → resumes from same count
How It Works
Clicking Start twice without this guard would create two intervals and double the speed. Set intervalId = null after clearing so you can detect a stopped state.
Example 4 — Pass Arguments to the Callback
Extra parameters after the delay are forwarded to your function.
JavaScript
function greet(name) {
console.log("Hello, " + name + "!");
}
setInterval(greet, 3000, "Alex");
Countdowns and limited polls often self-clear. Alternatively, use setTimeout chained recursively when you need variable delays between runs.
Applications
🚀 Common Use Cases
Live clocks and countdowns — update time display every second.
Image slideshows — advance slides on a timer (clear when hidden).
Polling APIs — fetch new data every N seconds (prefer WebSockets when possible).
Progress indicators — simulate loading steps in tutorials.
Simple animations — move elements in small steps (consider requestAnimationFrame for smooth motion).
Session timeouts — warn users before auto-logout.
🧠 What Happens When You Call setInterval()
1
Register timer
Browser stores callback + delay and returns an interval ID immediately.
Start
2
Script continues
Code after setInterval runs without waiting for the first tick.
Async
3
Callback fires
After delayMs, the function runs on the event loop—then again every delay.
Repeat
4
⏱
Until cleared
clearInterval(id) stops future ticks. Page close also stops timers.
Important
📝 Notes
Delay is minimum time, not exact—busy tabs may tick late.
Do not start a second interval without clearing the first—ticks will stack.
Long-running callback code can overlap the next tick if it exceeds the delay.
Background tabs may throttle timers to save battery (intervals > 1000ms are safer).
In Node.js, setInterval works similarly but IDs differ from browser numbers.
For visual animation at 60fps, prefer requestAnimationFrame over setInterval(fn, 16).
Compatibility
Browser Support
setInterval() has been supported since the earliest JavaScript timer APIs in browsers and matches universal runtime support.
✓ Universal · Standard API
setInterval()
Supported in Chrome, Firefox, Safari, Edge, Opera, Node.js, and WebViews. Works alongside clearInterval() everywhere timers exist.
100%Universal support
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
setInterval()Universal
Bottom line: Safe to use in any JavaScript environment with timers. Focus on storing IDs and calling clearInterval()—not polyfills.
Wrap Up
Conclusion
setInterval() repeats a callback every N milliseconds and returns an ID for cleanup. It powers clocks, slideshows, and polling—but only when you remember to stop timers you no longer need.
Pair it with clearInterval(), compare with setTimeout() for one-shot work, and reach for requestAnimationFrame() when smooth visuals matter most.
Use sensible delays (1000ms for clocks, not 1ms busy loops)
Clear intervals when components unmount in SPAs
❌ Don’t
Leave intervals running after the UI is removed
Stack multiple intervals on the same task
Assume ticks are perfectly precise to the millisecond
Run heavy work every few ms without throttling
Use setInterval for all animation—try rAF first
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about setInterval()
Your foundation for repeating timers in JavaScript.
5
Core concepts
📝01
Syntax
setInterval(fn, ms)
API
🔄02
Repeats
Until cleared.
Loop
🔖03
ID
Store return.
Handle
🛑04
Stop
clearInterval.
Cleanup
⏱05
vs timeout
Once vs repeat.
Compare
❓ Frequently Asked Questions
It schedules a function to run repeatedly after a fixed delay in milliseconds. Each call to setInterval() returns a numeric interval ID you can pass to clearInterval() to stop the loop.
A numeric interval ID (timer handle). Store it in a variable—e.g. const id = setInterval(tick, 1000)—so you can stop that specific interval later with clearInterval(id).
setTimeout(fn, ms) runs once after the delay. setInterval(fn, ms) runs again and again until you call clearInterval() or close the page. Use setTimeout for one-shot delays; setInterval for repeating tasks.
Yes. Extra arguments after the delay are forwarded to your function: setInterval(greet, 2000, "Alex"). Alternatively, use an arrow function: setInterval(() => greet("Alex"), 2000).
A running interval keeps firing forever, wasting CPU and battery. Clear it when the user navigates away, when a countdown finishes, or when the UI no longer needs updates.
For 60fps motion, requestAnimationFrame() is usually better—it syncs with the screen refresh. setInterval() is fine for clocks, polling, and simple step updates every second or more.
Did you know?
Browsers share one timer ID pool for setTimeout and setInterval, but you should still use clearInterval for intervals and clearTimeout for timeouts—matching the API that created the timer keeps code readable.