Debounce X Throttle
Mark Kop
Posted on December 11, 2019
At work, I had to solve a problem of some duplicate javascript events and found that it was an url hash being changed awkwardly sometimes.
As always at programming, there are several possible solutions and I've chosen to implement a Debounce Function.
Debounce x Throttle
Debounce and Throttle are both functions that help to limit the rate of callbacks being - well, - called.
Debounce
Debounce awaits for a given time of no action to be triggered.
One example of this use case I when you only want to search for content after a person stopped typing (haven't typed for 1 second+).
Throttle
Throttle has a fixed time window which it only accepts one action.
In the same use case, the content would be searched while the person is typing, but at every 1 second.
Debounce and Throttle on Javascript
At their simplest forms (that I know), they're pretty much straight forward. Debounce it's a Timeout that keeps resetting and Throttle a locked Timeout.
debounce: function(callback, wait) {
if (this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(() => callback(), wait);
},
throttle: function(callback, wait) {
if (!this.isWaiting) {
this.isWaiting = true;
callback();
setTimeout(() => (this.isWaiting = false), wait);
}
}
Instead of having the callback triggered after the input, it's possible to adapt these functions with an immediate effect. However, this "feature" and other utilities can be imported from the Lodash lib.
In fact, it's better and safer to use Lodash functions in your project if you need them. If you only need debounce and throttle, you migth run the following command:
npm i -g lodash-cli
lodash include = debounce, throttle
This tip was provided from this article.
Demo
To exemplify these functions, I've created a small Vue project which has both implementations. This is the demo and this is the repository.
Markkop / click-limiter
Example project on how to use simple debounce e throttle functions in Javascript/VueJS
Some use cases
- Window Resizing
- Hot Search inputs
- Repeating Events in general
More about Debounce and Throttle:
- CSS Tricks: Debouncing and Throttling Explained Through Examples
- Alligator.io: Throttling and Debouncing Events with Vue.js and lodash
- MatthewGerstman: Throttle and Debounce
- Walme Enginnering: Debounce and Throttle in Real Life Scenarios
- Programming With Mosh: JavaScript patterns: Throttle and Debounce
Posted on December 11, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.