Introduction:
In this blog, we will learn about two important concepts in JavaScript: debouncing and throttling. We will understand why we need them, their definitions, and how they can be implemented in our code. By the end of this blog, you will have a clear understanding of how to use debouncing and throttling to improve the performance of your JavaScript application.
Why do we need debouncing and throttling
In modern web applications, it is common to have UI elements that trigger events, such as buttons, checkboxes, or scroll bars. These events can cause the application to execute time-consuming tasks, such as fetching data from a server, updating the DOM, or rendering a chart. If these events occur frequently, they can overload the application and cause it to slow down or crash. To prevent this from happening, we need to use techniques like debouncing and throttling.
Debouncing
Debouncing is a technique for delaying the execution of a function until a certain amount of time has passed since the last time the function was called. This is useful in situations where a function may be called multiple times in quick succession, such as when handling user input.
Debouncing is commonly used in scenarios such as autocomplete search bars, where the function should be executed only after the user has finished typing. In this case, we can set a delay of, say, 500 milliseconds, so that the function is executed only after the user has paused typing for that duration.
Implementation of debouncing
function debounce(func, delay) {
let timer;
return function () {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, arguments);
}, delay);
}
}
let getData = ()=> {
console.log("Fetch data");
}
let delayGetData = debounce(getData,200);
//<input type="text" id="searchBox" onkeyup="delayGetData()" placeholder="Search...">
In this implementation, the debounce function takes two arguments: the function to be debounced and the delay time in milliseconds. The setTimeout function is used to execute the function after the specified delay time has passed. The clearTimeout function is used to cancel any pending execution of the function if another event is triggered before the delay time has elapsed.
The getData function is passed as a parameter, along with a delay of 200 milliseconds, to create the delayGetData function. This function can then be used as an argument for the onKeyUp event in a search box. When a user types in the search box, the delayGetData function is called, which uses the debounce function to ensure that the getData function is only executed once the user has finished typing. This helps to reduce the number of unnecessary API calls and improve the performance of the search feature.
Throttling
Throttling is similar to debouncing in that it limits the rate at which a function is executed. However, throttling does this by ensuring that the function is only executed at a certain interval, rather than waiting for a period of time after an event has occurred. It involves setting a fixed time interval and allowing the function to be called only once within that interval, regardless of how many times it is invoked.
Throttling is commonly used in scenarios such as scroll events, where the function should be executed at a fixed rate to update the UI, regardless of how fast the user scrolls. It is also useful for sending requests to a server or animating an element on a webpage.
Debouncing vs Throttling
Debouncing compares the time delay of a new event with respect to the last event fired, while throttling only allows the first event to be executed and blocks any subsequent events until a certain time interval has passed.
In the debouncing example, the function is executed once after a delay period has passed since the last event was fired. So, in this case, the function is executed once after the fifth event, since that is the last event fired before the delay period elapsed.
In the throttling example, the function is executed at a fixed interval, regardless of how many events are fired. So, in this case, the function is executed once at the first event, and then again after the interval has elapsed, regardless of the fact that more events are fired in the meantime.
Implementation of throttling
const throttle = (func, delay) => {
let isThrottled = false;
return function() {
if (!isThrottled) {
func.apply(this, arguments);
isThrottled = true;
setTimeout(() => {
isThrottled = false;
}, delay);
}
};
};
// Define the scroll event handler
const handleScroll = throttle(() => {
console.log('Scrolling...');
}, 200);
// Attach the event handler to the window scroll event
window.addEventListener('scroll', handleScroll);
In this implementation, the throttle function takes two arguments: the function to be throttled and the delay time in milliseconds. The isThrottled variable is initially set to false, indicating that the function is not currently being executed. When the returned function is invoked, it first checks whether the function is currently being executed by checking the isThrottled flag. If the function is not being executed, the function is invoked immediately using the func.apply method, and isThrottled is set to true to indicate that the function is currently being executed.
A setTimeout function is used to set a timer that will reset the isThrottled flag to false after the specified delay time has passed. This ensures that the function is not called too frequently and is instead called at a set interval.
Then the throttle function is used to create a throttled version of the handleScroll function, which logs a message to the console when the window is scrolled. The throttled function is created by passing handleScroll and a delay of 200 milliseconds to the throttle function.
The resulting throttled function is then attached to the scroll event of the window object, so that it will be called whenever the window is scrolled. The throttle function ensures that the handleScroll function is only called at most once every 200 milliseconds, even if the user scrolls the window more frequently than that. This can help to reduce the frequency of expensive or time-consuming operations that might be triggered by the scroll event.
Conclusion
In summary, debouncing and throttling are two techniques used to improve website performance by limiting the rate at which a function is executed. Debouncing is used to delay the execution of a function until a certain amount of time has passed, while throttling ensures that the function is only executed at a fixed interval. By using these techniques, we can create smoother and more responsive websites that provide a better user experience.