DEV Community

Cover image for Debounce X Throttle
Mark Kop
Mark Kop

Posted on

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 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 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;
    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.


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:

Top comments (2)

jhenrisilva profile image
Juliano Henrique

Mds euu nem sabia que existia uma rede social de desenvolvedores. Eu tava olhando os comentários de feedback do teste da linx e vi que você compartilhou esse artigo. Alias, mandou bemzásso na resolução do bug, gostei muito do artigo.

heymarkkop profile image
Mark Kop

Esse é muito massa mesmo. Ele é tipo um medium na real, mas bem mais legal ahuahua. Valeu pelo comentário!