Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active January 16, 2021 03:39
Show Gist options
  • Save LeanSeverino1022/60f99962f45bf90354231904ce980878 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/60f99962f45bf90354231904ce980878 to your computer and use it in GitHub Desktop.
debounce snippet #vanillajs

f you're using React, you'll want to wrap your handler in useCallback.. more in the article

Context

There are many events in JS that trigger super quickly.

When you scroll the page, or resize the window, or move your mouse, the browser captures dozens and dozens of events per second.

In many cases, you don't need to capture every single intermediate step; you're only interested in capturing the end state (when the user finishes scrolling, or finishes resizing the window).

Debouncing is a strategy that lets us improve performance by waiting until a certain amount of time has passed before triggering an event. When the user stops triggering the event, our code will run.

In some cases, this isn't necessary. But, if any network requests are involved, or if the DOM changes (eg. re-rendering a component), this technique can drastically improve the smoothness of your application.

Me: great stuff by Josh Comeau in this article. Check the article out for more knowledge

const debounce = (callback, wait) => {
let timeoutId = null;
return (...args) => {
window.clearTimeout(timeoutId);
timeoutId = window.setTimeout(() => {
callback.apply(null, args);
}, wait);
};
}
//usage
const handleMouseMove = debounce((ev) => {
// Do stuff with the event!
}, 250);
window.addEventListener('mousemove', handleMouseMove);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment