DebounceTime & Debounce in Angular

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.

Use Case of Debounce Operators

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.

DebounceTime

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

Where dueTime The timeout duration in milliseconds.

How it works

  • First, we assign a timeout duration (dueTime) to the Debouncetime operator.
  • The Debouncetime operator starts counting time after it receives a value.
  • If the source observable emits a value before the timeout duration, then counting is reset to zero & started again.
  • When the timeout duration elapses the operator emits the last value and the counting stops.
  • Counting starts again when the operators receive another value.

DebounceTime Example

The following DebounceTime example shows how to use the operator to listen for input field changes

Source Code

Optimizing HTTP Request using debounceTime

The following example shows how you can send an HTTP GET Request using the combination of switchMap, distinctUntilChanged() & debounceTime.

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.

Debounce

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.

Debounce Example

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.

Source Code

You can also customize the delay. In the following example, we increase the delay by 100ms after every keystroke.

Source Code

Reference

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top