JavaScript Closure Memory Leak Prevention Utilities
JavaScript closure memory leak prevention best practices for beginners - ready-to-use utility functions for detecting and preventing memory leaks in closures.
JavaScript Closure Memory Leak Prevention Utilities
JavaScript closure memory leak prevention best practices for beginners includes using practical utility functions. These ready-to-use code snippets help detect, prevent, and manage memory leaks in closures effectively.
Memory Leak Detection Utility #
Monitor memory usage and detect potential leaks in your JavaScript applications.
Safe Event Handler Creator #
Utility for creating event handlers that automatically clean up references.
// Safe event handler utility with automatic cleanup
function createSafeEventHandler(element, eventType, handler, options = {}) {
const { autoCleanup = false, timeout = 30000 } = options;
// Weak reference tracking
const handlerRef = new WeakRef(handler);
let isActive = true;
function safeHandler(event) {
const fn = handlerRef.deref();
if (fn && isActive) {
fn.call(this, event);
} else {
// Handler was garbage collected or deactivated
cleanup();
}
}
function cleanup() {
if (isActive) {
element.removeEventListener(eventType, safeHandler);
isActive = false;
}
}
element.addEventListener(eventType, safeHandler);
// Auto cleanup after timeout
if (autoCleanup) {
setTimeout(cleanup, timeout);
}
return {
cleanup,
isActive: () => isActive
};
}
// Usage example
const button = document.createElement('button');
const handler = createSafeEventHandler(button, 'click', function() {
console.log('Button clicked');
}, { autoCleanup: true, timeout: 10000 });
// Manual cleanup when needed
// handler.cleanup();
Closure Scope Cleaner #
Utility to help clean up closure variables and prevent memory leaks.
Timer Management Utility #
Prevent memory leaks from timers and intervals with automatic cleanup.
// Timer manager utility for preventing timer-related memory leaks
class TimerManager {
constructor() {
this.timers = new Set();
this.intervals = new Set();
}
setTimeout(callback, delay, ...args) {
const wrappedCallback = (...callbackArgs) => {
this.timers.delete(timerId);
callback(...callbackArgs);
};
const timerId = setTimeout(wrappedCallback, delay, ...args);
this.timers.add(timerId);
return {
id: timerId,
clear: () => this.clearTimeout(timerId)
};
}
setInterval(callback, interval, ...args) {
const intervalId = setInterval(callback, interval, ...args);
this.intervals.add(intervalId);
return {
id: intervalId,
clear: () => this.clearInterval(intervalId)
};
}
clearTimeout(timerId) {
clearTimeout(timerId);
this.timers.delete(timerId);
}
clearInterval(intervalId) {
clearInterval(intervalId);
this.intervals.delete(intervalId);
}
clearAll() {
this.timers.forEach(id => clearTimeout(id));
this.intervals.forEach(id => clearInterval(id));
this.timers.clear();
this.intervals.clear();
}
getActiveCount() {
return {
timers: this.timers.size,
intervals: this.intervals.size
};
}
}
// Usage example
const timerManager = new TimerManager();
// Create managed timers
const timer1 = timerManager.setTimeout(() => {
console.log('Timer 1 executed');
}, 1000);
const interval1 = timerManager.setInterval(() => {
console.log('Interval 1 tick');
}, 500);
// Check active timers
console.log('Active timers:', timerManager.getActiveCount());
// Cleanup all timers when component unmounts
// timerManager.clearAll();
Component Lifecycle Manager #
Comprehensive utility for managing component lifecycle and preventing memory leaks.
Usage Best Practices #
- Always use cleanup utilities when creating closures that reference large objects
- Monitor memory usage during development with the MemoryMonitor utility
- Use WeakRef and WeakMap for object references that can be garbage collected
- Implement automatic cleanup with timeout-based cleanup for long-running applications
- Track component lifecycle using the ComponentManager for complex applications
Summary #
These JavaScript closure memory leak prevention utilities provide practical tools for beginners to implement memory leak prevention best practices. Use these utilities to automatically manage event listeners, timers, and component lifecycle to prevent common memory leak scenarios in closure-heavy applications.
Remember to always clean up resources explicitly and monitor memory usage during development to catch potential leaks early.