DebounceTime & Debounce In Angular

DebounceTime & Debounce In Angular

In this article,  we will learn how to use DebounceTime and Debounce with examples. The Angular RxJs Operators DebounceTime and Debounce are the Angular RxJs Operators. After a given length of time has passed since the last value, both broadcast values from the source are observable. Both emit only the most recent value and ignore any previous values.

Use Case of Debounce Operators

One of the most prominent use cases for Debounce Operators is typeahead/autocomplete fields.

We need to listen to the user type in the typeahead field and send an HTTP request to the back end to receive a list of possible values. If we submit HTTP requests for every keystroke, we'll end up making a lot of unnecessary service calls.

We use the Debounce Operators to delay sending an HTTP Request until the user stops typing. Unnecessary HTTP queries will be eliminated as a result of this.

DebounceTime

After a set period of time has passed with no other value showing on the source observable, the Debouncetime emits the last received value from the source observable.

Syntax

debounceTime<T>(dueTime: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T>

Where dueTime The duration of the timeout in milliseconds.

How it works

  • First, we give the Debouncetime operator a timeout duration (dueTime).
  • After receiving a value, the Debouncetime operator begins counting time.
  • If a value is emitted by the source observable before the timeout period has expired, counting is reset to zero and the process begins again.
  • The operator emits the last value and the counting stops when the timeout duration expires.
  • When the operators receive a new value, the counting process begins again.

DebounceTime Example

The DebounceTime example below demonstrates how to use the operator to listen for changes in input fields.

import { Component, VERSION } from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
import { Observable, Subscription } from "rxjs";
import { debounceTime } from "rxjs/operators";
 
@Component({
  selector: "my-app",
  template: `
    <form [formGroup]="mform">Name: <input formControlName="name" /></form>
  `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
 
  mform: FormGroup = new FormGroup({
    name: new FormControl()
  });
 
  obs:Subscription;
 
  ngOnInit() {
    this.obs=this.mform.valueChanges
      .pipe(debounceTime(500))
      .subscribe(data => console.log(data));
  }
  
  ngOnDestroy() {
    this.obs.unsubscribe();
  }
}

Sending HTTP GET Request

The following example shows how to use switchMap and debounceTime to send an HTTP GET Request.

ngOnInit() {
  this.obs=this.mform.valueChanges
    .pipe(
      debounceTime(500),
      switchMap(id => {

        console.log(id)
        return this.http.get(url)

      })
    )
    .subscribe(data => console.log(data));
}

Debounce

The Debounce operator is similar to the DebounceTime operator, except that the time span is provided by another observable. We can set the time span dynamically by using the Debounce.

Debounce Example

The following example is identical to the previous one. Instead of using the hardcoded time span, we use the interval operator to build a new observable.

import { Component, VERSION } from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
import { debounce } from "rxjs/operators";
import { interval, Subscription } from "rxjs";
 
@Component({
  selector: "my-app",
  template: `
    <form [formGroup]="mform">Name: <input formControlName="name" /></form>
  `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  mform: FormGroup = new FormGroup({
    name: new FormControl()
  });
 
  obs:Subscription
 
  ngOnInit() {
    this.obs=this.mform.valueChanges
      .pipe(debounce(() => interval(500)))
      .subscribe(data => console.log(data));
  }
 
  ngOnDestroy() {
    this.obs.unsubscribe()
  }
  
}

You can also change the delay time. After each keystroke, we increase the delay by 100ms in the following example.

delay = 500;

obs: Subscription;

ngOnInit() {
  this.obs = this.mform.valueChanges
    .pipe(
      debounce(() => {
        this.delay = this.delay + 100;
        console.log(this.delay);
        return interval(this.delay);
      })
    )
    .subscribe(data => console.log(data));
}

Conclusion

In this article,  we learned how to use DebounceTime and Debounce with examples.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post