0
0
AngularHow-ToBeginner · 3 min read

How to Use debounceTime in RxJS for Angular

Use the debounceTime operator in RxJS to delay emissions from an observable by a specified time, ignoring values that come in too quickly. It helps reduce rapid event firing, such as user input, by only emitting the latest value after the delay.
📐

Syntax

The debounceTime operator takes a single argument: the delay time in milliseconds. It returns a new observable that emits values only after the specified delay has passed without another emission.

  • debounceTime(delay: number): delay in milliseconds
typescript
import { debounceTime } from 'rxjs/operators';

observable.pipe(
  debounceTime(300)
);
💻

Example

This example shows how to use debounceTime with an input event to wait for the user to stop typing for 500ms before processing the input value.

typescript
import { Component } from '@angular/core';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'app-search',
  template: `
    <input type="text" (input)="onInput($event)" placeholder="Type to search..." />
    <p>Search term: {{ searchTerm }}</p>
  `
})
export class SearchComponent {
  private inputSubject = new Subject<string>();
  searchTerm = '';

  constructor() {
    this.inputSubject.pipe(
      debounceTime(500)
    ).subscribe(value => {
      this.searchTerm = value;
    });
  }

  onInput(event: Event): void {
    const input = event.target as HTMLInputElement;
    this.inputSubject.next(input.value);
  }
}
Output
When typing in the input box, the displayed search term updates only after 500ms of no typing.
⚠️

Common Pitfalls

One common mistake is not subscribing to the observable returned by debounceTime, so no values are emitted. Another is using debounceTime on a cold observable without triggering it properly. Also, setting the delay too low or too high can cause unexpected behavior.

Wrong: Not subscribing to the debounced observable.

typescript
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

const subject = new Subject<string>();

// This does nothing because no subscription
subject.pipe(debounceTime(300));

// Correct way
subject.pipe(debounceTime(300)).subscribe(value => console.log(value));

subject.next('Hello');
Output
Hello (logged after 300ms delay)
📊

Quick Reference

OperatorPurposeParameterExample Usage
debounceTimeDelays emissions, emits latest after silencedelay in msobservable.pipe(debounceTime(300))
distinctUntilChangedEmits only if value changednoneobservable.pipe(distinctUntilChanged())
throttleTimeEmits first value, then ignores others for delaydelay in msobservable.pipe(throttleTime(300))

Key Takeaways

Use debounceTime to delay observable emissions until a pause in events.
Always subscribe to the observable after applying debounceTime to receive values.
Set the delay time thoughtfully to balance responsiveness and noise reduction.
debounceTime is ideal for user input scenarios like search boxes to reduce API calls.
Combine debounceTime with other operators like distinctUntilChanged for better control.