Memory leaks in JavaScript often happen due to event listeners or large objects lingering in memory. Here’s a code snippet to help detect memory leaks by tracking memory usage over time:
function monitorMemoryUsage() {
if (window.performance && window.performance.memory) {
const memoryUsage = window.performance.memory.usedJSHeapSize / 1024 / 1024;
console.log(`Memory usage: ${memoryUsage.toFixed(2)} MB`);
} else {
console.warn('Memory usage tracking is not supported in this environment.');
}
}
setInterval(monitorMemoryUsage, 5000); // Run every 5 seconds