-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebouncer.js
62 lines (52 loc) · 1.48 KB
/
debouncer.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
export default class Debouncer {
_lastRun = 0;
_firstRequest = 0;
_lastRequest = 0;
constructor(callback, delay = 100, maxDelays = 2) {
if (typeof callback !== 'function') {
throw new TypeError('Function is required');
}
this._cb = callback;
this._delay = delay;
this._maxDelays = maxDelays;
}
_now() {
this._lastRun = Date.now();
this._cb();
this.clear();
}
_later() {
const now = Date.now();
const delta = now - this._lastRequest;
const totalDelta = now - this._firstRequest;
const maxDelay = this._delay * this._maxDelays;
const maxTimeout = Math.min(maxDelay - totalDelta, this._delay - delta);
if (this._lastRun && maxTimeout > 0) {
this._timeout = setTimeout(() => this._later(), maxTimeout);
} else {
this._now();
}
}
run(immediately = false) {
const now = Date.now();
this._lastRequest = now;
if (!this._firstRequest) {
this._firstRequest = now;
}
if (immediately) {
this._now();
} else if (!this._timeout) {
this._timeout = setTimeout(() => this._later(), this._delay);
}
}
flush() {
if (this._timeout) {
this._now();
}
}
clear() {
this._firstRequest = 0;
this._lastRequest = 0;
this._timeout = clearTimeout(this._timeout);
}
}