These Common JavaScript Mistakes Reduce Performance Drastically
Updated: February 19, 2022•2 min read
How can we prevent our web app from leaking memory? We have to avoid the retention of unnecessary resources. Let’s look at the most common scenarios where this might happen.
Timer Listeners
Let’s look at the setInterval
timer. It is a commonly used Web API feature.
The return of setInterval
is an interval ID which we can use to cancel the interval. We can call clearInterval
once the Component unmounts.
Event Listeners
When using addEventListener
, we need to use removeEventListener
to remove it.
Observers
“The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.” — MDN Web Docs
Once you are done observing the object, you need to cancel out the monitor process.
Holding DOM References
DOM nodes are not free from memory leaks either. You need to be careful not to hold references of them.
Conclusion
It is recommended to periodically run the browser profiler tools on your web application. That is the only way to be sure that nothing is leaking and left behind. The Chrome Developer performance
tab is the place to start detecting some anomalies. After you have spotted an issue, you can dig deeper into it with the profiler
tab by taking snapshots and comparing them.
Don’t forget to clap 👏 in the comment section below if you learned something new