24 Jul 2024
1 min

debounce – RxJS Reference

debounce

debounce delays the values emitted by a source until the duration Observable emits a value or completes. If within this time a new value arrives, the previous pending value is dropped and the duration Observable is re-subscribed. In this way debounce keeps track of the most recent value and emits that most recent value using the duration observable as an indicator of where to do that.

The operator works in the following way:

  1. when new value arrives, execute a function to get the duration Observable
  2. subscribe to the duration Observable
  3. keep the value and discard old ones if exists
  4. when the duration Observable emits a value or completes, pass the stored value to the observer
  5. if new value comes before the duration Observable emits or complets, run step 1 again

Usage

This operator is mostly used for events that can be triggered tens or even hundreds of times per second. The most common examples are DOM events such as scrolling, mouse movement, and keypress. When using debouce you only care about the final state. For example, current scroll position when a user stops scrolling, or a final text in a searchbox after a user stops typing in characters. In effect, using the operator allows grouping multiple sequential events into a single one and hence execute the callback just once. This can greatly improve performance.

Common scenarios for a debounce are resize, scroll, and keyup/keydown events. In addition, you should consider wrapping any interaction that triggers excessive calculations or API calls with a debounce.

Here’s an example of using debounce on an input:

const inputElement = document.createElement('input');
document.body.appendChild(inputElement);

fromEvent(inputElement, 'input')
   .pipe(
       debounce(() => interval(500)),
       map((event: any) => event.target.value)
   ).subscribe(val => console.log(val));

Playground

Additional resources

See also

Frequently asked questions

How do I debounce an input event in RxJS?

Use the debounce() operator with a duration selector, such as debounce(() => interval(500)), on the fromEvent(inputElement, 'input') stream. Each new event cancels the pending value and re-subscribes to the duration Observable, so only the latest value is emitted once the user stops typing for 500 ms. Map the event to event.target.value after the debounce to read the final text.

What is the difference between debounce() and debounceTime() in RxJS?

debounce() takes a function that returns a duration Observable, which decides when the pending value is emitted. debounceTime() is a shorthand that takes a fixed number of milliseconds instead. Use debounce() when the delay must be dynamic or driven by another stream, and debounceTime() when a simple fixed time window is enough.

When should I use debounce() instead of throttleTime() in RxJS?

Use debounce() when you only care about the final state after a burst of events, such as the last scroll position or the final text in a search box. throttleTime() instead emits at a regular rate during the burst, which suits cases where you need intermediate updates. Both reduce how often your callback runs, but they produce different emission patterns.

Why does debounce() not emit a value when my source keeps emitting?

debounce() only emits when the duration Observable emits or completes before a new source value arrives. If the source emits continuously faster than the duration window, each new value discards the previous one and re-subscribes the duration Observable, so nothing is passed downstream. Shorten the duration, or use auditTime() or throttleTime() if you need periodic output during continuous activity.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.