Debounce and Throttle in JavaScript

Debounce and throttle are two concepts that we can use in JavaScript to increase the control of our function executions, specially useful in event handlers.

Both techniques answer the same question “How often a certain function can be called over time?” in different ways:

  • Debounce: Think of it as “grouping multiple events in one”. Imagine that you go home, enter in the elevator, doors are closing… and suddenly your neighbor appears in the hall and tries to jump on the elevator. Be polite! and open the doors for him: you are debouncing the elevator departure. Consider that the same situation can happen again with a third person, and so on… probably delaying the departure several minutes.
  • Throttle: Think of it as a valve, it regulates the flow of the executions. We can determine the maximum number of times a function can be called in certain time. So in the elevator analogy.. you are polite enough to let people in for 10 secs, but once that delay passes, you must go!

Event handlers without debouncing or throttling are like one-person-capacity elevators: not that efficient.

Use cases for debounce

Use it to discard a number of fast-pace events until the flow slows down. Examples:

  • When typing fast in a textarea that will be processed: you don’t want to start to process the text until user stops typing.
  • When saving data to the server via AJAX: You don’t want to spam your server with dozens of calls per second.

Use cases for throttle

Same use cases than debounce, but you want to warranty that there is at least some execution of the callbacks at certain interval

  • If that user types really fast for 30 secs, maybe you want to process the input every 5 secs.
  • It makes a huge performance difference to throttle handling scroll events. A simple mouse-wheel movement can trigger dozens of events in a second. Even Twitter had once problems with scroll events, so learn from others mistake and avoid this easy pitfall.

Here is visual guide to these concepts.

Resource

https://redd.one/blog/thinking-in-functions-higher-order-functions

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect