JavaScript Closure Memory Leak Prevention Best Practices Code
Ready-to-use JavaScript closure memory leak prevention best practices utilities and functions for optimizing memory usage in your apps.
JavaScript Closure Memory Leak Prevention Best Practices Code
These JavaScript closure memory leak prevention best practices utilities provide ready-to-use functions for managing memory efficiently in closure-heavy applications. Each utility implements proven patterns to prevent common memory leaks.
Copy and customize these utilities to optimize memory usage in your JavaScript projects while maintaining clean, functional code patterns.
Safe Closure Factory #
Creates closures with automatic cleanup and memory management:
DOM Reference Manager #
Manages DOM element references in closures to prevent memory leaks:
Event Listener Cleanup Utility #
Automatically manages event listeners in closures with proper cleanup:
// Event listener manager with automatic cleanup
function createEventManager() {
const listeners = new Map();
let isActive = true;
function addListener(element, event, handler, options = {}) {
if (!isActive) return null;
const listenerId = `${event}_${Date.now()}_${Math.random()}`;
const wrappedHandler = function(...args) {
if (!isActive) return;
handler.apply(this, args);
};
element.addEventListener(event, wrappedHandler, options);
listeners.set(listenerId, {
element,
event,
handler: wrappedHandler,
options
});
return listenerId;
}
function removeListener(listenerId) {
const listener = listeners.get(listenerId);
if (listener) {
listener.element.removeEventListener(
listener.event,
listener.handler,
listener.options
);
listeners.delete(listenerId);
}
}
function cleanup() {
isActive = false;
listeners.forEach((listener, id) => {
removeListener(id);
});
listeners.clear();
}
return {
addListener,
removeListener,
cleanup,
getListenerCount: () => listeners.size,
isActive: () => isActive
};
}
WeakMap Cache Manager #
Uses WeakMap for automatic garbage collection of closure data:
Timer Management Utility #
Manages timers in closures with automatic cleanup:
Memory Monitor Utility #
Monitors memory usage in closure-heavy applications:
// Memory monitoring utility for closure debugging
function createMemoryMonitor(options = {}) {
const {
interval = 5000,
threshold = 50, // MB
onThresholdExceeded = null
} = options;
let isActive = true;
let measurements = [];
const maxMeasurements = 100;
function getCurrentMemory() {
if (!performance.memory) return null;
const { usedJSHeapSize, totalJSHeapSize, jsHeapSizeLimit } = performance.memory;
return {
used: Math.round(usedJSHeapSize / 1024 / 1024), // MB
total: Math.round(totalJSHeapSize / 1024 / 1024), // MB
limit: Math.round(jsHeapSizeLimit / 1024 / 1024), // MB
timestamp: Date.now()
};
}
function measureMemory() {
if (!isActive) return;
const memory = getCurrentMemory();
if (memory) {
measurements.push(memory);
// Keep only recent measurements
if (measurements.length > maxMeasurements) {
measurements.shift();
}
// Check threshold
if (memory.used > threshold && onThresholdExceeded) {
onThresholdExceeded(memory, measurements);
}
}
}
const monitorInterval = setInterval(measureMemory, interval);
function getStats() {
if (measurements.length === 0) return null;
const recent = measurements.slice(-10);
const avgUsed = recent.reduce((sum, m) => sum + m.used, 0) / recent.length;
const maxUsed = Math.max(...recent.map(m => m.used));
const minUsed = Math.min(...recent.map(m => m.used));
return {
current: getCurrentMemory(),
average: Math.round(avgUsed),
max: maxUsed,
min: minUsed,
measurements: measurements.length
};
}
function cleanup() {
isActive = false;
clearInterval(monitorInterval);
measurements = [];
}
return {
getStats,
getCurrentMemory,
cleanup,
getMeasurements: () => [...measurements]
};
}
Usage Best Practices #
- Always call cleanup methods when components unmount or are no longer needed
- Use WeakMap for object-keyed caches that should be garbage collected
- Extract only necessary data from DOM elements instead of storing references
- Monitor memory usage in development to catch leaks early
- Set maximum execution limits on repeated operations
These utilities implement JavaScript closure memory leak prevention best practices and can be customized for your specific use cases while maintaining optimal memory management.
Learn the theory behind these utilities | View comprehensive closure tutorial