Learn RxJS
Search…
debounce

signature: debounce(durationSelector: function): Observable

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

πŸ’‘ Though not as widely used as debounceTime, debounce is important when the debounce rate is variable!
​​
​
​

Examples

Example 1: Debounce on timer
1
// RxJS v6+
2
import { of, timer } from 'rxjs';
3
import { debounce } from 'rxjs/operators';
4
​
5
//emit four strings
6
const example = of('WAIT', 'ONE', 'SECOND', 'Last will display');
7
/*
8
Only emit values after a second has passed between the last emission,
9
throw away all other values
10
*/
11
const debouncedExample = example.pipe(debounce(() => timer(1000)));
12
/*
13
In this example, all values but the last will be omitted
14
output: 'Last will display'
15
*/
16
const subscribe = debouncedExample.subscribe(val => console.log(val));
Copied!
Example 2: Debounce at increasing interval
1
// RxJS v6+
2
import { interval, timer } from 'rxjs';
3
import { debounce } from 'rxjs/operators';
4
​
5
//emit value every 1 second, ex. 0...1...2
6
const interval$ = interval(1000);
7
//raise the debounce time by 200ms each second
8
const debouncedInterval = interval$.pipe(debounce(val => timer(val * 200)));
9
/*
10
After 5 seconds, debounce time will be greater than interval time,
11
all future values will be thrown away
12
output: 0...1...2...3...4......(debounce time over 1s, no values emitted)
13
*/
14
const subscribe = debouncedInterval.subscribe(val =>
15
console.log(`Example Two: ${val}`)
16
);
Copied!

Additional Resources

Last modified 9mo ago