Blog>
Snippets

Debounced Input with RxJS for Performance

Show how to debounce user input with RxJS in Angular forms to limit the number of events processed, thereby optimizing performance on mobile.
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

@Component({
  selector: 'app-debounced-input',
  template: `<input type='text' [formControl]='debouncedInputControl'>`,
})
export class DebouncedInputComponent {
  debouncedInputControl = new FormControl();

  constructor() {
    this.debouncedInputControl.valueChanges
      .pipe(
        debounceTime(500), // Wait for 500 ms pause in events
        distinctUntilChanged() // Only emit if value is different from previous value
      )
      .subscribe((value) => {
        // Handle the debounced input value
        console.log('Debounced Input:', value);
      });
  }
}
This Angular component sets up a form control with RxJS debounceTime and distinctUntilChanged operators to limit the number of processed input events. The debounceTime operator waits for a 500 millisecond pause in input events before emitting the latest value, while distinctUntilChanged ensures that only distinct values are emitted. This setup is useful in optimizing performance, particularly on mobile devices where processing power is more limited.