CodePark/ questions / Functional patterns
START PRACTICINGPRACTICE
Frontend question · JavaScript › Functional patterns

What is the difference between debounce and throttle? Give a use case for each.

Both limit how often a function runs when events fire quickly. Debounce waits until the events stop. Throttle runs at a steady rate while the events continue.

Debounce:

  • Each new call resets a timer.
  • The function runs only once there has been a quiet period of wait ms since the last call.
  • Like an elevator door: it closes only when people stop walking in.
  • Use it when you only care about the final state. Examples: search-as-you-type requests, checking input after the user stops typing, and recalculating layout after a resize ends.

Throttle:

  • The function runs at most once per interval, no matter how many events arrive.
  • So it keeps running at a steady rate during continuous activity.
  • Use it for scroll position tracking, infinite-scroll checks, drag or mousemove handlers, and rate-limited API calls.

Both often have leading and trailing options. These decide whether the first call or the last call in a burst runs.

In short: debounce turns a burst into one call. Throttle samples the burst at a fixed rate.

  • Debounce runs after the events stop for wait ms. Each call resets the timer.
  • Throttle runs at most once per interval during continuous events.
  • Use debounce for search input, autosave and the end of a resize.
  • Use throttle for scroll, mousemove and drag.
  • Leading and trailing options decide whether the first or last call runs.