-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebounce.js
More file actions
51 lines (46 loc) · 1.05 KB
/
Debounce.js
File metadata and controls
51 lines (46 loc) · 1.05 KB
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
function debounce(callback, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
callback(...args);
}, delay);
};
}
function throttle(callback, delay) {
let inThrottled = false;
return function (...args) {
if (!inThrottled) {
inThrottled = true;
callback.apply(this, args);
setTimeout(() => {
inThrottled = false;
}, delay);
}
};
}
// If leading is true, it will invoke immediately after function call
// If trailing is true, it is class debounce
// If both are true, it will invoke at first and then it will invoke at last
function debounceWithTraingAndLeading(
cb,
time,
{ leading = true, trailing = true }
) {
let timerId;
return function (...args) {
const isLeadingCall = leading && !timerId;
if (isLeadingCall) {
cb(...args);
}
if (timerId) {
clearInterval(timerId);
}
timerId = setTimeout(() => {
if (trailing && !isLeadingCall) {
cb(...args);
}
timerId = null;
}, time);
};
}