Debounce X Throttle

heymarkkop

Mark Kop

Posted on December 11, 2019

Debounce X Throttle

Duplicate event on hash change

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

Debouncing

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+).

Debounced input

Debounce example

Throttle

ThrottleParrot

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.

Throttled input

Throttle example

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);
},
Enter fullscreen mode Exit fullscreen mode
throttle: function(callback, wait) {
  if (!this.isWaiting) {
    this.isWaiting = true;
    callback();
    setTimeout(() => (this.isWaiting = false), wait);
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

GitHub logo 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:

💖 💪 🙅 🚩
heymarkkop
Mark Kop

Posted on December 11, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related