**setInterval** repeatedly fires a callback every `interval` milliseconds until **clearInterval** is called. Like setTimeout, the interval is a minimum. If the callback takes longer than the interval, calls can stack up. Prefer `setTimeout` recursion for dynamic intervals or long-running callbacks.
1Understanding setInterval()
setInterval repeatedly fires a callback every interval milliseconds until clearInterval is called. Like setTimeout, the interval is a minimum. If the callback takes longer than the interval, calls can stack up. Prefer setTimeout recursion for dynamic intervals or long-running callbacks.
For reliable intervals with long callbacks, use recursive setTimeout: after the callback runs, schedule the next one. This prevents piling up.
// Countdown timer
let count = 10;
const timer = setInterval(() => {
console.log('T-' + count);
count--;
if (count < 0) {
clearInterval(timer);
console.log('Liftoff! 🚀');
}
}, 1000);2Practical Example
Here is a real-world application of setInterval() showing how it is used in production JavaScript code.
// Reliable interval with recursive setTimeout
function reliableInterval(fn, delay) {
let id;
function tick() {
fn();
id = setTimeout(tick, delay); // schedule next AFTER completion
}
id = setTimeout(tick, delay);
return () => clearTimeout(id); // return cancel function
}
const stop = reliableInterval(() => console.log('ping'), 1000);3Best Practices
Follow these guidelines when working with setInterval():
1. Always store the ID and call clearInterval when done
2. Use clearInterval in cleanup (useEffect return, component unmount)
3. For long-running callbacks, use recursive setTimeout instead
Tip: For reliable intervals with long callbacks, use recursive setTimeout: after the callback runs, schedule the next one. This prevents piling up.
// Countdown timer
let count = 10;
const timer = setInterval(() => {
console.log('T-' + count);
count--;
if (count < 0) {
clearInterval(timer);
console.log('Liftoff! 🚀');
}
}, 1000);