Debounce and Throttling: What They Are and When to Use Them (2024)

Debounce and Throttling: What They Are and When to Use Them (2)

If you are a web developer, you might have encountered situations where you need to optimize the performance of your code that runs repeatedly within a short period of time. For example, you might have a search bar that fetches suggestions from the backend as the user types, or a resize event handler that adjusts the layout of your page. In these cases, you don’t want to execute your code too often, as it might cause unnecessary network requests, a laggy user interface, or high CPU usage.

To solve this problem, you can use two techniques called debouncing and throttling. These techniques allow you to control the rate at which your code is executed, and reduce the number of times it is called. In this article, we will explain what debouncing and throttling are, how they differ, and how to implement them in JavaScript.

What is Debouncing?

Debouncing is a technique that delays the execution of a function until the user stops performing a certain action for a specified amount of time. For example, if you have a search bar that fetches suggestions from the backend as the user types, you can debounce the function that makes the API call, so that it only runs after the user stops typing for a few seconds. This way, you can avoid making too many API calls that might overload your server or return irrelevant results.

To implement debouncing in JavaScript, you can use a timer variable to track the delay period. You can use the setTimeout function to set a timer that will execute your function after the delay period. You can also use the clearTimeout function to cancel the timer if the user performs the action again before the delay period ends. This way, you can ensure that your function only runs once after the user stops performing the action.

Here is an example of how to implement debouncing in JavaScript:

// A function that makes an API call with the search query
function searchHandler(query) {
// Make an API call with search query
getSearchResults(query);
}
// A debounce function that takes a function and a delay as parameters
function debounce(func, delay) {
// A timer variable to track the delay period
let timer;
// Return a function that takes arguments
return function(…args) {
// Clear the previous timer if any
clearTimeout(timer);
// Set a new timer that will execute the function after the delay period
timer = setTimeout(() => {
// Apply the function with arguments
func.apply(this, args);
}, delay);
};
}
// A debounced version of the search handler with 500ms delay
const debouncedSearchHandler = debounce(searchHandler, 500);
// Add an event listener to the search bar input
searchBar.addEventListener("input", (event) => {
// Get the value of the input
const query = event.target.value;
// Call the debounced search handler with the query
debouncedSearchHandler(query);
});

In this example, we have a searchHandler function that makes an API call with the search query. We also have a debounce function that takes a function and a delay as parameters, and returns a debounced version of that function. We use this debounce function to create a debouncedSearchHandler function with 500ms delay. We then add an event listener to the search bar input, and call the debouncedSearchHandler function with the input value. This way, we can ensure that we only make one API call after the user stops typing for 500ms.

What is Throttling?

Throttling is a technique that limits the execution of a function to once in every specified time interval. For example, if you have a resize event handler that adjusts the layout of your page, you can throttle the function that updates the layout, so that it only runs once every 100ms. This way, you can avoid running your code too frequently, which might cause janky user interface or high CPU usage.

To implement throttling in JavaScript, you can use a flag variable to track whether the function is already running or not. You can use the setTimeout function to set a timer that will reset the flag after the time interval. You can also use an if statement to check whether the flag is true or not before executing your function. This way, you can ensure that your function only runs once in every time interval.

Here is an example of how to implement throttling in JavaScript:

// A function that updates the layout of the page
function updateLayout() {
// Update layout logic
}
// A throttle function that takes a function and an interval as parameters
function throttle(func, interval) {
// A flag variable to track whether the function is running or not
let isRunning = false;
// Return a function that takes arguments
return function(…args) {
// If the function is not running
if (!isRunning) {
// Set the flag to true
isRunning = true;
// Apply the function with arguments
func.apply(this, args);
// Set a timer that will reset the flag after the interval
setTimeout(() => {
// Set the flag to false
isRunning = false;
}, interval);
}
};
}
// A throttled version of the update layout function with 100ms interval
const throttledUpdateLayout = throttle(updateLayout, 100);
// Add an event listener to the window resize event
window.addEventListener("resize", () => {
// Call the throttled update layout function
throttledUpdateLayout();
});

In this example, we have an updateLayout function that updates the layout of the page. We also have a throttle function that takes a function and an interval as parameters, and returns a throttled version of that function. We use this throttle function to create a throttledUpdateLayout function with 100ms interval. We then add an event listener to the window resize event, and call the throttledUpdateLayout function. This way, we can ensure that we only update the layout once every 100ms.

What is the Difference Between Debouncing and Throttling?

The main difference between debouncing and throttling is that debouncing executes the function only after some cooling period, while throttling executes the function at a regular interval. Debouncing and throttling are both useful techniques to improve the performance of your code, but they have different use cases and effects.

Debouncing is useful when you want to delay the execution of your code until the user stops performing a certain action. For example, you can use debouncing for autocomplete, where you want to wait for the user to stop typing before fetching suggestions from the backend. Debouncing can reduce the number of times your code is executed, but it can also introduce some latency in your user interface.

Throttling is useful when you want to limit the execution of your code to a certain frequency. For example, you can use throttling for resize, where you want to update the layout of your page at a fixed rate. Throttling can improve the responsiveness of your user interface, but it can also cause some loss of information or accuracy in your code.

Conclusion

Debouncing and throttling are two techniques that can help you optimize the performance of your code that runs repeatedly within a short period of time. Debouncing delays the execution of your code until the user stops performing a certain action for a specified amount of time. Throttling limits the execution of your code to once in every specified time interval. Both techniques have different use cases and effects, and you should choose the one that suits your needs best.

Debounce and Throttling: What They Are and When to Use Them (2024)

References

Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 6354

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.