Repetitive Asynchronous Tasks with JavaScript's setInterval()

setInterval() queues a callback repeatedly on a schedule. On one JavaScript agent, an interval callback cannot interrupt another callback that is still executing. The practical risk is asynchronous work: the interval does not await a promise or request started by the previous callback, so a later tick can start another operation before the first one settles.
What is setInterval()?
setInterval is a global JavaScript method which can be used to call a function or execute a code snippet repeatedly, with a fixed delay between each call. It's part of the Window interface in the browser environment, making it widely available for web‑based scripts.
Basic Syntax
setInterval(callback, delay, ...args);callback: the function to execute.delay: The interval time in milliseconds between each function call....args: Additional arguments to pass to the function.
Using setInterval in JavaScript
Starting an Interval
To start an interval, you simply call setInterval, providing the function to be executed and the interval time, like this:
const sayHello = (): void => {
console.log('Hello, world!');
};
setInterval(sayHello, 2000); //=> 'Hello, world!' every 2 secondThis example will feel extremely familiar if you've also read my previous article about setTimeout, they are quite genuinely virtually identical. However, whereas the example code I used there would output Hello, World! once, after two seconds (2000 milliseconds), in this instance it will output it repeatedly, once every two seconds.
Stopping an Interval
setInterval() returns an identifier for the timer. Keep that value and pass it to clearInterval() when the repeated work should stop; the callback itself does not need to be assigned to a variable for cancellation to work.
const sayHello = (): void => {
console.log('Hello, world!');
};
// set as 'interval' this time
const interval = setInterval(sayHello, 1000);
// we can stop this again like this:
clearInterval(interval);setInterval in React
In dynamic web applications, especially those using frameworks like React or Vue, managing intervals requires careful attention to the application's lifecycle. You need to ensure that intervals are cleared when components or pages are unloaded to prevent unwanted side effects or resource leaks.
This is very simple if ‑ for example ‑ you are setting the interval within a useEffect hook:
useEffect(() => {
const timer = setInterval(() => {
// Outputs 'tick' every second:
console.log('tick');
}, 1000);
// makes sure that the timer is cleaned up in the return
return () => clearInterval(timer);
}, []);Here, the Effect sets up an interval that requests a tick every second. The empty dependency array means ordinary re‑renders do not set it up again. In development, React Strict Mode deliberately runs an extra setup‑and‑cleanup cycle to check that the cleanup works.
The returned cleanup passes the timer identifier to clearInterval(). It stops that setup's interval on unmount and during the Strict Mode check, so each setup has a matching teardown.
Considerations and Best Practices
Clearing the Interval
: It's important to clear the interval when it's no longer needed to prevent unnecessary function executions and potential memory leaks.- Minimum delay: deeply nested timers are clamped to at least 4 ms after five nesting levels. Background tabs and other browser policies can impose longer delays; 4 ms is not a universal interval schedule.
Delay Accuracy
: Like setTimeout, intervals are not guaranteed to execute precisely at the specified delay due to JavaScript's single‑threaded nature and event loop.
Wrapping Up
setInterval() is suitable when work should be initiated on a fixed schedule and overlapping asynchronous operations are acceptable or prevented separately. Where one operation must finish before the next begins, schedule a recursive setTimeout() after that operation settles. Cancellation and page visibility still need explicit handling in either design.