Debounce Overview

The debounce operator defers each value emitted by the source until a duration Observable either emits or completes. Should a fresh value arrive during this waiting period, the previously held value is discarded and the duration Observable is subscribed to anew. Therefore, debounce consistently tracks only the latest value, using the duration Observable as the signal for when to release that value downstream.

The operational flow of the operator is as follows:

  1. Upon receiving a new value, a function is invoked to produce the duration Observable
  2. Subscription to that duration Observable is established
  3. The current value is retained, and any prior stored values are removed
  4. Once the duration Observable emits or completes, the held value is forwarded to the observer
  5. If another value appears before the duration Observable reacts, the process restarts from step 1

Practical Applications

This operator proves especially useful for events that fire frequently, sometimes dozens or hundreds of times each second. Typical cases include browser events like scrolling, mouse movement, and typing. With debounce, the focus is on the final outcome — for instance, the scroll position after the user pauses, or the complete text entered in a search field once typing stops. Effectively, the operator coalesces a sequence of rapid events into one, triggering the callback only once per burst. Such behavior can yield significant performance gains.

Typical situations where a debounce fits well are resize, scroll, and keyup/keydown handlers. Moreover, any logic that leads to heavy computation or excessive network requests should be considered for debouncing.

Below is an example demonstrating debounce applied to an input field:

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

Interactive Demonstration

Further Reading