Demo:  debounceTime

debounceTime emits the latest value, if no new value arrives for the specified pause duration.

debounceTime(pauseDurationInMilliseconds)

Note: It emits the last value immediately, as there would be no new value.

//Emit with delay equals to num*0.1sec
const source = of(2,5,15,25,4,45,6,6)
        .pipe(concatMap(v=>of(v).pipe(delay(100*v))));

//Emit if no new value arrives for next 2 secs
const timeIntervalFilter = debounceTime(2000);

//Gap between 15-25 is 2.5 sec & 4-45 is 4.5 sec
const output = source.pipe(timeIntervalFilter).subscribe(v=>console.log(v))
What is happening ?

In this demo, we have used a debounceTime of 2 seconds to filter the source items.

This will emit the latest values, only if no new value arrives for next 2 seconds.

So, if look at the output :

  • We can see 15 appears because 25 arrives after 2.5 seconds.
  • Again, 4 appears because 45 arrives after 4.5 seconds.
  • Then the last value appears immediately, considering the next value will never arrive.
  • No other value appeared, because a new value arrived before 2 seconds for each of them.
More on : debounceTime

Like auditTime, debounceTime is another way to sample the incoming changes.

  • Whereas auditTime captures the changes after the specified time intervals,
  • debounceTime waits for the changes to settle down for a given small interval of time.

What do these differences mean ?


Usages

1. Capture the Change, when it Settles Down.

Let's say we are adding an auto-complete or a typeahead search taking input from a input search box.

  • With a delayed sampling as provided by auditTime, we are able to take the samples of the latest text as the user keeps typing.

It's fine if our searchs are on local cache and not so resource intensive. But, in case it is not so, we can filter our searches further using debounceTime.

  • With debounceTime, we will wait for the user to stop typing for sometime say 0.5 sec, while the user keeps thinking for further text, we can take that text to find our suggestions for him. So, instead of proactive suggestions as given by auditTime, we can use debounceTime to provide suggestions where the user more likely needs it.

Opting between any of the above two ways of capturing the changes is quite easy with the declarative syntaxes as shown below.