Anjan Karmaker
anjankarmakar15@gmail.com
Debouncing is a technique used to control how often a particular function is executed in response to frequent events. It ensures that the function is called only after a certain amount of time has passed since the last event. In this blog, we'll explore the concept of debouncing and demonstrate its implementation using a practical example in JavaScript.
Understanding Debouncing
Imagine a search bar on a webpage that fetches search results as the user types. Without debouncing, every keystroke triggers a new search request, potentially overwhelming the server and causing unnecessary network traffic. Debouncing addresses this problem by delaying the execution of the function until the user has finished typing.
Debouncing involves setting a timer that delays the function execution. If another event occurs before the timer expires, the timer is reset. This ensures that the function only fires after a certain quiet period.
Practical Example: Implementing Debounce in JavaScript
Let's dive into a practical example to demonstrate how to implement debouncing using JavaScript. We'll use the provided code as a starting point and explain each component.
const searchInput = document.getElementById("search");
function getData(data) {
console.log("Fetching data.... ", data);
}
function debounceFun(getData, delay) {
let time;
return (...args) => {
let self = this;
if (time) clearTimeout(time);
time = setTimeout(() => {
getData.apply(self, args);
}, delay * 1000);
};
}
const optimizeFun = debounceFun(getData, 1);
searchInput.addEventListener("keyup", (e) => {
optimizeFun(e.target.value);
});
In this example, we have a search input element and a getData
function that simulates fetching data based on the search query.
debounceFun
function takes two arguments: the function to be debounced (getData
) and a delay in seconds (delay
).debounceFun
, a closure is returned. This closure maintains a reference to the time
variable, which stores the timer ID.keyup
event on the search input), the optimizeFun
(debounced version of getData
) is called with the search value.optimizeFun
, the existing timer is cleared using clearTimeout
if it exists. Then, a new timer is set using setTimeout
.getData
function until the specified delay
has passed since the last event.Benefits of Debouncing: