0%

Debounce And Throttle

Debounce And Throttle

They are all done the closing package

  • Debounce

    The same action is triggered consecutively over a period of time, executing only the last triggered action.

  • Throttle

    The same action is triggered consecutively over a period of time, executing the action at each interval.

Debounce and Throttle

Principle of implementation

Debounce

1
2
3
4
5
6
7
8
9
10
const debounce = (fn, delay) => {
let timer = null;

return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => {
fn(args);
}, delay);
};
};

Throttle

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
// timer
const throttleTimer = (fn, delay) => {
let timer = null;

return (...args) => {
if (!timer) {
timer = setTimeout(() => {
fn(args);
timer = null;
}, delay);
}
};
};

// timestamp
const throttleTimestamp = (fn, delay) => {
let startTime = Date.now();

return (...args) => {
let curTime = Date.now();
let remainTime = delay - (curTime - startTime);
if (remainTime < 0) {
fn(args);
startTime = Date.now();
}
};
};

// time + timestamp
const throttle = (fn, delay) => {
let timer = null;
let startTime = Date.now();

return () => {
let curTime = Date.now();
let remainTime = delay - (curTime - startTime);
clearTimeout(timer);
if (remainTime > 0) timer = setTimeout(fn, delay);
else {
fn(...args);
startTime = Date.now();
}
};
};

References

详解防抖函数(debounce)和节流函数(throttle)

-------------The end of this article, thanks for reading-------------