Demo: debounce
debounce is similar to debounceTime.
In this case, we need to specify the debounce time using an observable such as a timer, instead of the time in milliseconds as in debounceTime.
debounce(v => innerObservable)
//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 = debounce(v => timer(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))
The debounce operator is very similar to the debounceTime. Both ensure there are no new value for the specified time, before it emits the value.
The debounce uses an internal observable to decide the debounce interval. For instance, we have used a timer that fires after 2 seconds for our demo.
On arrival of a new input, this timer starts to check if another value arrives before it fires.
If no new value arrives, the last value will be emitted! But, in case a new value arrives before the timer fires:
- The timer will be reset for the new value and.
- The previous value will not be emitted!
if we look at the output here:
- We can see 15 appears because 25 arrives after 2.5 seconds, which is after the timer fires.
- Similarly, 4 appears because 45 arrives after 4.5 seconds.
- Then the last value appears immediately, because timer is just for 2 seconds whereas no value is supposed arrive anymore.
- For all other values, because a new value arrived before the timer fires, none of them were emitted.
In short, this operator ensures there are no new value for the specified time before it emits the value.