debounce

signature: debounce(durationSelector: function): Observable

Discard emitted values that take less than the specified time, based on selector function, between output.


:bulb: Though not as widely used as debounceTime,
debounce is important when the debounce rate is variable!


Examples

Example 1: Debounce on timer

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { timer } from 'rxjs/observable/timer';
  3. import { debounce } from 'rxjs/operators';
  4. //emit four strings
  5. const example = of('WAIT', 'ONE', 'SECOND', 'Last will display');
  6. /*
  7. Only emit values after a second has passed between the last emission,
  8. throw away all other values
  9. */
  10. const debouncedExample = example.pipe(debounce(() => timer(1000)));
  11. /*
  12. In this example, all values but the last will be omitted
  13. output: 'Last will display'
  14. */
  15. const subscribe = debouncedExample.subscribe(val => console.log(val));
Example 2: Debounce at increasing interval

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { timer } from 'rxjs/observable/timer';
  3. import { debounce } from 'rxjs/operators';
  4. //emit value every 1 second, ex. 0...1...2
  5. const interval = interval(1000);
  6. //raise the debounce time by 200ms each second
  7. const debouncedInterval = interval.pipe(debounce(val => timer(val * 200)));
  8. /*
  9. After 5 seconds, debounce time will be greater than interval time,
  10. all future values will be thrown away
  11. output: 0...1...2...3...4......(debounce time over 1s, no values emitted)
  12. */
  13. const subscribe = debouncedInterval.subscribe(val =>
  14. console.log(`Example Two: ${val}`)
  15. );

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/debounce.ts