Using Debounce on the Resize Event

Not long ago, I was working on a project that had an element positioned relative to the edge of the viewport.

To make it work, I needed to constantly track the position of that element. My initial code looked something like this:

const Elements = (elements) => {
	elements.forEach((element) => {
		const elementRect = element.getBoundingClientRect();
		element.style.setProperty('--offset-left', `${elementRect.left}px`);
	});
};

const trackElement = () => {
	Elements(document.querySelectorAll('.some-elements'));
};

trackElement();
window.addEventListener('resize', trackElement);

The problem with this approach is that every time the user resizes the browser window, the trackElement function fires repeatedly—sometimes dozens of times per second. If you’re tracking multiple elements, this can quickly become inefficient and lead to noticeable performance issues.

The fix is to use debounce. Debouncing is a technique that limits how often a function runs. Instead of firing continuously, the function only executes once after a set delay from the last time it was triggered.

For this, I used the debounce package from npm. Here’s how I updated the code:

import debounce from 'debounce';

const Elements = (elements) => {
	elements.forEach((element) => {
		const elementRect = element.getBoundingClientRect();
		element.style.setProperty('--offset-left', `${elementRect.left}px`);
	});
};

const trackElement = () => {
	Elements(document.querySelectorAll('.some-elements'));
};

trackElement();
window.addEventListener('resize', debounce(trackElement, 200));

Now, trackElement only runs 200 milliseconds after the user stops resizing the window. This small change makes the code more efficient and keeps performance smooth, even with a lot of elements to track.

Leave a Reply

Your email address will not be published. Required fields are marked *