How to use a Debounce function in JavaScript
Table of Contents
If an event is particularly slow to occur, you can use a debounce function to prevent it from firing too often.
This can limit the number of times the event can trigger and therefore improve overall performance.
In this post, we'll take a look at how to use a debounce function in JavaScript.
How to use a debounce function
First, let's start off with an example event that fires often and can be taxing to execute:
JAVASCRIPTwindow.addEventListener("scroll", () => {
console.log("Expensive scroll event");
});
With this event listener registered, every time the user scrolls the page, the event will fire.
Let's now wrap this in a debounce function.
A debounce function is a higher-order function that will take your desired function as a parameter and return a new function that is controlled by a timeout.
Let'see our debounce function:
JAVASCRIPTconst debounce = (callback, delay) => {
let timeout;
return function debounced(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
clearTimeout(timeout);
callback(...args);
}, delay);
};
};
Now let's use these together:
JAVASCRIPTconst debounce = (callback, delay) => {
let timeout;
return function debounced(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
clearTimeout(timeout);
callback(...args);
}, delay);
};
};
const debouncedScroll = debounce(() => {
console.log("Expensive scroll event");
}, 1000);
window.addEventListener("scroll", debouncedScroll);
Now every time the user scrolls the page, the event will only fire after 1 second has passed, instead of every time the user scrolls.
Conclusion
In this post, we've covered how to use a debounce function in JavaScript.
Simply pass in a callback function and a delay in milliseconds to your debounce function and it will return a new function that will only fire after the delay has passed.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications