-
Notifications
You must be signed in to change notification settings - Fork 2
/
debounce.ts
48 lines (42 loc) · 1.12 KB
/
debounce.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { Operator, Observer } from '../index';
import { createSource } from '../sources';
import subscribe from '../utils/subscribe';
/**
* Emits a value from the source only when source didn't emit a value during a particular time
*
* @param duration - duration in milliseconds of time to wait before emit a value
* @return callbag operator
*
* @public
*/
function debounce<I>(duration: number): Operator<I, I> {
return source => {
return createSource((next, complete, error) => {
let lastValue: I;
let timeout = 0;
const observer: Observer<I> = {
next: value => {
clearTimeout(timeout);
lastValue = value;
timeout = setTimeout(() => {
next(lastValue);
}, duration);
},
error: err => {
clearTimeout(timeout);
error(err);
},
complete: () => {
clearTimeout(timeout);
complete();
},
};
const unsubscribe = subscribe(source)(observer);
return () => {
clearTimeout(timeout);
unsubscribe();
};
});
};
}
export default debounce;