Introduction
In this article, you will learn the concept of Memory leaks in setInterval.
As you know, Many developers use setInterval(), but few know it can silently cause memory leaks. Now, let’s understand this.
What is setInterval?
setInterval() is used to repeatedly execute a function after a fixed delay.
Example:
setInterval(() => {
console.log("Running...");
}, 1000);
This runs every 1 second (1000 mili seconds) unless stopped.
How Memory Leaks Happen
There are many reasons for memory leaks.
- The interval keeps running even after the component/page is removed.
- References are not cleared.
- Timers stack repeatedly.
- In frameworks like React, Angular, or Vue.js, component unmount/destroy doesn’t clear the interval.
Example: In the example below, you can see we define an interval but do not destroy it after use.
function startTimer() {
setInterval(() => {
console.log("Still running...");
}, 1000);
}
What will happen: the memory keeps increasing.
What is the correct way to Prevent Memory Leaks?
Always clear the interval when not needed.
const intervalId = setInterval(() => {
console.log("Running safely...");
}, 1000);
// Clear when not needed
clearInterval(intervalId);
How to fix the memory issue in Angular?
You can destroy the interval through ngOnDestroy
intervalId: any;
ngOnInit() {
this.intervalId = setInterval(() => {
console.log("Running...");
}, 1000);
}
ngOnDestroy() {
clearInterval(this.intervalId);
}
How to fix the memory issue in React?
Use useEffect Cleanup
useEffect(() => {
const id = setInterval(() => {
console.log("Running...");
}, 1000);
return () => clearInterval(id);
}, []);
What are Best Practices?
- Always store the interval ID.
- Always clear on component destroy.
- Avoid nested intervals.
- Prefer setTimeout recursion if needed.
- Use RxJS interval in Angular projects.
Real Life Example of live stock price dashboard
In this example, I will show you a memory leak caused by setInterval that happens in dashboards or live data applications.
Suppose you have a live stock price dashboard where the price updates every 2 seconds.
Example: Without clearing the setInterval
function startPriceUpdates() {
setInterval(() => {
console.log("Fetching latest stock price...");
// API call to fetch stock price
}, 2000);
}
startPriceUpdates();
In the above example, each time the page loads, a new interval starts, but the old one is never cleared.
- Multiple intervals keep running in the background.
- The browser keeps allocating memory.
- API calls increase unnecessarily.
- The application becomes slower over time.
Correct Approach when using setInterval
You should clear the interval when it is no longer needed.
Example:
let intervalId;
function startPriceUpdates() {
intervalId = setInterval(() => {
console.log("Fetching latest stock price...");
}, 2000);
}
function stopPriceUpdates() {
clearInterval(intervalId);
}
Now, when the user leaves the page or the component is destroyed, you can call:
stopPriceUpdates();
Interview Questions
Q 1: What is a memory leak in JavaScript?
Ans: A memory leak occurs when memory that is no longer needed is not released
Q 2: How can setInterval cause a memory leak?
Ans: If an interval continues running even after the related component or page is removed, it keeps consuming memory and executing code repeatedly.
Q 3: How can you prevent memory leaks caused by setInterval?
Ans: You can prevent memory leaks by storing the interval ID and stopping it using clearInterval() when the interval is no longer required.
Q 4: What is the difference between setInterval and setTimeout regarding memory leaks?
Ans: setInterval runs repeatedly until cleared, which makes it more likely to cause memory leaks if not stopped. setTimeout runs only once.
Conclusion
setInterval is used to run the tasks repeatedly, like auto-refreshing data, animations, or background checks. However, if intervals are not properly cleared, they can lead to memory leaks and performance issues.
In Single Page Applications (SPA) like React, Angular, or Vue, intervals may continue running even after components are removed. This causes unnecessary CPU usage and increased memory consumption.
To avoid this problem, developers should always store the interval ID and clear it using clearInterval() when the task is finished, or the component is destroyed.