Give me an easy way to create a memory leak in Angular and how to fix it. Eg setInterval()?
SituationalFrontend Angular developerSenior Angular DeveloperAngular DeveloperUsing setInterval() without proper cleanup is a common way to create a memory leak in Angular. For instance, if I set an interval in a component to fetch data every few seconds and forget to clear it in the ngOnDestroy() lifecycle hook, it will keep running even after the component is destroyed, leading to a memory leak.
To fix this, I would store the interval ID returned by setInterval() and call clearInterval() in the ngOnDestroy() method. This ensures that the interval stops when the component is no longer in use, freeing up memory. I would judge success by monitoring the application’s memory usage before and after implementing this fix, ensuring it remains stable over time.