debounceTime delays the values emitted by a source for the given due time. If within this time a new value arrives, the previous pending value is dropped and the timer is reset. In this way
debounceTime keeps track of most recent value and emits that most recent value when the given due time is passed.
The operator works in the following way:
- when new value arrives schedule a new interval
- remember the value and discard old ones if exists
- when the interval ends, emit the value
- if new value comes before the interval ends, run step 1 again
By default it uses
setInterval through AsyncScheduler under the hood for scheduling.
The following diagram demonstrates this sequence of steps:
UsageLink to this section
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
debouceTime 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
debounceTime on an input:
const inputElement = document.createElement('input'); document.body.appendChild(inputElement); fromEvent(inputElement, 'input') .pipe( debounceTime(500), map((event: any) => event.target.value) ).subscribe(val => console.log(val));
PlaygroundLink to this section
Additional resourcesLink to this section
- Official documentation
- How to debounce an input while skipping the first entry
- Rx.js Operators, Part II