These Common JavaScript Mistakes Reduce Performance Drastically

Profile iamgeDan Fleser

Updated: February 19, 20222 min read

These Common JavaScript Mistakes Reduce Performance Drastically

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

Hi,
👋
I'm

Dan Fleser

Profile iamge

Full-time web developer since 2014. I recently switched from an 8-5 job to freelancing, which is going great.