How do I detect and fix memory leaks in JavaScript?
Asked on Sep 03, 2024
Answer
Detecting and fixing memory leaks in JavaScript involves identifying unused memory that is not released. You can use tools like Chrome DevTools to help with this process.
// Example of a memory leak due to a forgotten interval
const intervalId = setInterval(() => {
console.log("This runs every second");
}, 1000);
// Fix by clearing the interval when it's no longer needed
clearInterval(intervalId);
Additional Comment:
✅ Answered with JavaScript best practices.- Use Chrome DevTools' "Memory" tab to take heap snapshots and analyze memory usage.
- Common causes of memory leaks include forgotten timers, event listeners, or global variables.
- To fix leaks, ensure you clean up intervals, listeners, and references when they are no longer needed.
Recommended Links:
← Back to All Questions