-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathindex.js
88 lines (67 loc) · 1.8 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import mimicFunction from 'mimic-function';
const debounceFunction = (inputFunction, options = {}) => {
if (typeof inputFunction !== 'function') {
throw new TypeError(`Expected the first argument to be a function, got \`${typeof inputFunction}\``);
}
const {
wait = 0,
maxWait = Number.POSITIVE_INFINITY,
before = false,
after = true,
} = options;
if (wait < 0 || maxWait < 0) {
throw new RangeError('`wait` and `maxWait` must not be negative.');
}
if (!before && !after) {
throw new Error('Both `before` and `after` are false, function wouldn\'t be called.');
}
let timeout;
let maxTimeout;
let result;
const debouncedFunction = function (...arguments_) {
const context = this; // eslint-disable-line unicorn/no-this-assignment
const later = () => {
timeout = undefined;
if (maxTimeout) {
clearTimeout(maxTimeout);
maxTimeout = undefined;
}
if (after) {
result = inputFunction.apply(context, arguments_);
}
};
const maxLater = () => {
maxTimeout = undefined;
if (timeout) {
clearTimeout(timeout);
timeout = undefined;
}
if (after) {
result = inputFunction.apply(context, arguments_);
}
};
const shouldCallNow = before && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (maxWait > 0 && maxWait !== Number.POSITIVE_INFINITY && !maxTimeout) {
maxTimeout = setTimeout(maxLater, maxWait);
}
if (shouldCallNow) {
result = inputFunction.apply(context, arguments_);
}
return result;
};
mimicFunction(debouncedFunction, inputFunction);
debouncedFunction.cancel = () => {
if (timeout) {
clearTimeout(timeout);
timeout = undefined;
}
if (maxTimeout) {
clearTimeout(maxTimeout);
maxTimeout = undefined;
}
};
return debouncedFunction;
};
export default debounceFunction;