DebounceTime & Debounce are the Angular RxJs Operators. Both emit values from the source observable, only after a certain amount of time has elapsed since the last value. Both emit only the latest value and discard any intermediate values. In this tutorial, we will learn how to use both DebounceTime & Debounce with examples.
The typeahead/autocomplete fields are one of the most common use cases for Debounce Operators
As the user types in the typeahead field, we need to listen to it and send an HTTP request to the back end to get a list of possible values. If we send HTTP requests for every keystroke, we make numerous unneeded calls to the server.
By using the Debounce Operators, we wait until the user pauses typing before sending an HTTP Request. This will eliminate unnecessary HTTP requests.
The Debouncetime emits the last received value from the source observable after a specified amount of time has elapsed without any other value appearing on the source Observable
Syntax
debounceTime<T>(dueTime: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T>
Where dueTime The timeout duration in milliseconds.
The following DebounceTime example shows how to use the operator to listen for input field changes
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();
}
}
The following example shows how you can send an HTTP GET Request using the combination of switchMap, distinctUntilChanged() & debounceTime.
ngOnInit() {
this.obs=this.mform.valueChanges
.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap(id => {
console.log(id)
return this.http.get(url)
})
)
.subscribe(data => console.log(data));
}
In the above example, debounceTime(500) waits for the user to stop typing for 500 ms (i.e. half a second). The distinctUntilChanged() will fire only if the value is changed from the previous value. The switchMap() operator unsubscribes from the previous request and sends the new HTTP request.
The Debounce operator is similar to the DebounceTime operator, but another observable will provide the time span. By using the Debounce, we can set the time span dynamically.
The following example works the same as the previous example. Instead of using the hardcoded time span, we create a new observable using the interval operator.
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 customize the delay. In the following example, we increase the delay by 100ms after every keystroke.
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));
}