Orion's Studio.

防抖和节流

2024/03/23

防抖

返回一个函数,防止函数在短时间内多次触发,只有在最后一次触发后才执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const debounce = (fn, delay = 2000, immediate = true) => {
let timer = null;
return function (...args) {
if (immediate) {
if (!timer) {
fn.apply(this, args);
} else {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
}, delay);
return;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
};

节流

返回一个函数,防止函数在短时间内多次触发,在规定时间内只会执行一次。

1
2
3
4
5
6
7
8
9
10
11
const throttle = (fn, delay = 2000) => {
let timer = null;
return function (...args) {
if (!timer) {
fn.apply(this, args);
timer = setTimeout(() => {
timer = null;
}, delay);
}
};
};
CATALOG
  1. 1. 防抖
  2. 2. 节流