Debouncing and Throttling are two ways to control how many times we allow a function to be executed in the time. Having a debounced or throttled version of our function is particularly useful when we are attaching the function to DOM’s event because, in these scenarios, we may invoke functions when it isn’t necessary.
Debounce and throttle are two programming techniques that can save the day when it comes to performance. It’s important to know when to use them — but also important to know when not to use them.
Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. For example, “execute this function only if 100 milliseconds have passed without it being called.”
In other words: The debounce technique allows us to “group” multiple raised sequential functions into a single function.
Throttling enforces a maximum number of times a function can be called overtime. For example, “execute this function at most once every 100 milliseconds.”
In other words: By using the throttle, we don’t allow our function to execute more than once every X milliseconds.
When to use each
Use debounce when you want your function to postpone its next execution until after X milliseconds have elapsed since the last time it was invoked.
Use throttle when you need to ensure that events fire at given intervals. Some use cases for each follow:
- Measure the scroll position of the page — The browser will fire the
scrollbinding event every single time the user scrolls, which can result in many events per
scroll. If the binding event performs several repaints, this spells bad news for the end-user; layout reflows and repaints are expensive, especially when you are redrawing large parts of the view, as is the case when there is a
- Wait until the user stops resizing the window — Window resizes operations cause various child elements to update themselves by resizing and reorganizing themselves. By throttling, you can delay the resize events and fire fewer of those resizing events.
- Fire Ajax calls under control and avoids unnecessary network request handling — for example, in case of searching for external data, wait until the end-user stops typing by using debounce. If you are sending log data frequently, use a throttle.