
Explain Debouncing with Examples
20 January, 2023
2
2
0
Contributors
Debouncing is a JavaScript technique that helps limit the number of times a function is called in a given period. It can be helpful when you have an event triggered many times in quick succession, and you only want the function to be executed once or a certain number of times.
One way to implement debouncing in JavaScript is to use the setTimeout
function to delay the execution until a certain amount of time has passed. Here is an example of a debounce function that will only allow the given function to be called once every 500 milliseconds:
function debounce(fn, delay) {
let timer;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => fn.apply(context, args), delay);
}
}
You can use the debounce function like this:
const debouncedFn = debounce(function() {
console.log('This function is debounced');
}, 500);
// The function will only be called once every 500 milliseconds
debouncedFn();
debouncedFn();
debouncedFn();
There are several use cases for debouncing in JavaScript. Some examples are:
- Autocomplete search: When a user types into a search input field, you should send a request to the server to get suggestions. However, if the user types quickly, you might send many requests in a short amount of time, which is wasteful. By debouncing the request function, you can ensure that it is only sent once the user has stopped typing for a certain amount of time.
- Window resizing: When the user resizes their browser window, the
resize
event is triggered multiple times. If you have a function that needs to be called every time the window is resized, you can debounce it to avoid doing unnecessary calculations and DOM updates. - Scrolling: The
scroll
event is triggered multiple times as the user scrolls. If you have a function that needs to be called every time the user scrolls, such as lazy loading images, you can debounce it to avoid overloading the browser with too many requests. - Form validation: When a user types into a form input, you should validate the input and show an error message if necessary. However, if the user types quickly, you might validate the input multiple times in a short time. Debouncing the validation function can prevent this and make the experience more smooth.
- Drag and drop events: when the user is holding an object and moving it over a drop zone, multiple events will trigger each time the user moves the object. Debouncing the function will reduce the number of events triggering.
These are just a few examples, but debouncing can be useful in any situation where you have an event triggered multiple times in quick succession, and you only want a function executed once or a certain number of times.
Further Reading
- Find more about debouncing from this article by Josh W Comeau.