DEV Community

Cover image for How to Use RXJS Debounce Time With Angular
Manoj Prasanna  πŸš€
Manoj Prasanna πŸš€

Posted on

How to Use RXJS Debounce Time With Angular

In this article, I will guide you through the concept of debounce time and how to use it in your Angular applications with RxJS operators. Debounce time helps efficiently manage user input and optimize application performance. I'll provide a step-by-step guide to help you understand how to use debounce time and improve your application's performance and usability. First, let's explore what debounce time is.

What is Debounce Time?

Debounce time is a technique used to prevent an event from being triggered too frequently. This can be especially useful in situations where you want to avoid the user spamming a button or sending an excessive number of requests to a server. For instance, let's consider an input search field similar to Google's search bar. If a user starts typing in the field, we don't want to immediately send a request for each character they type. Instead, we can use debounce time to delay the request and ensure it is sent only after the user has paused typing for a certain duration. By applying debounce time, we can efficiently manage user input and prevent unnecessary API calls, which can lead to a better user experience and improved application performance. Now let's see how to use the debounce time for our Angular application.

How to Use Debounce Time in Angular

Most Common approach is to apply debounce time by using the rxjs library. Which Angular already includes as a dependency.

And now Let's explore those operators and pipes.

debounceTime() pipe
The debounceTime pipe is a built-in Angular pipe that can be used to debounce an event. To use the debounceTime pipe, you need to pass the debounce time in milliseconds as an argument
distinctUntilChanged()
distinctUntilChanged is an operator that is used to filter out consecutive emissions of the same value from an Observable. This can be useful in situations where you want to prevent the Observable from emitting the same value multiple times in a row.
takeUntil()
The takeUntil() operator in Angular is used to automatically unsubscribe from an Observable when another Observable emits a value. This can be useful in situations where you want to prevent an Observable from emitting values after a certain point.

In this tutorial, I will show you how to use RxJS to apply debounce time to an input event. I will demonstrate way to implement debounce time in your application.

Step 01: Create the template file

In your template content

<div class="content" role="main">
  <h1>Welcome</h1>
  <h2>How to Use Debounce Time to Improve the Performance of Your Angular Applications</h2>
  <input type="text" 
  [(ngModel)]="inputText" 
  placeholder="Input something" (input)="onSearch()" />
<br/>
</div>
Enter fullscreen mode Exit fullscreen mode

Above, I have implemented an input field with an input event that triggers the debounce function.

Step 02 : Import the required modules

Open the component file and import the necessary modules

import { Component, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { debounceTime, takeUntil } from 'rxjs/operators';
Enter fullscreen mode Exit fullscreen mode

I import the required modules: Subject and the debounceTime operator from rxjs/operators.

Step 03 : Implement the debounce logic

Create a private searchSubject,which will emit values whenever the onSearch method is called.

export class AppComponent {
  title = 'CodeSandbox';
  private searchSubject = new Subject<string>();
  inputText: string = '';
  ngOnInit() {

  }
  onSearch() {
    this.searchSubject.next(this.inputText);
  }

}

Enter fullscreen mode Exit fullscreen mode

In the ngOnInit lifecycle hook, I have established a subscription to the searchSubject. Within this subscription, I utilize the debounceTime operator to introduce a delay before processing the emitted events. This delay allows the timer to reset if the user continues typing within the specified time (in this case, 300ms). However, if the user pauses typing for the specified time, the searchSubject emits the latest value, triggering the execution of the performSearch method with that value.

export class DebounceExampleComponent implements OnInit, OnDestroy {
  private searchSubject = new Subject<string>();
  private readonly debounceTimeMs = 300; // Set the debounce time (in milliseconds)

  ngOnInit() {
    this.searchSubject.pipe(debounceTime(this.debounceTimeMs)).subscribe((searchValue) => {
      this.performSearch(searchValue);
    });
  }

  ngOnDestroy() {
    this.searchSubject.complete();
  }

  onSearch(searchValue: string) {
    this.searchSubject.next(searchValue);
  }

  performSearch(searchValue: string) {
    // Perform the actual search operation here
    console.log('Performing search for:', searchValue);
    // ... Your search logic ...
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion
Debounce time is a powerful technique to control the frequency of event execution in Angular applications. By strategically delaying the processing of input events, you can optimize the performance and responsiveness of your application. Whether it's handling user inputs or other frequent events, debounce time is a valuable tool to have in your Angular development toolbox.

That’s It!

Of course you probably want to see this in action. Here’s a working demo for you to fork or play with:

Thanks for reading the whole story ❀

Top comments (1)

Collapse
 
gregorgonzalez profile image
Gregor Gonzalez

Love how angular has a built in solution for every problem