Appearance
手写防抖和节流函数
区别
debounce
: 防抖,遇到高频率触发的函数,但只需要在一定时间内执行一次的,用防抖; throttle
: 节流, 遇到高频率触发的函数,但只需要在一定时间内执行的,用节流。
总结
debounce
和throttle
各有特点,在不同 的场景要根据需求合理的选择策略。如果事件触发是高频但是有停顿时,可以选择debounce
; 在事件连续不断高频触发时,只能选择throttle
,因为debounce
可能会导致动作只被执行一次,界面出现跳跃。
防抖
ts
function debounce(fn: Function, delay: number = 500) {
let timer: any = null;
return function (...args: any) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, ...args);
timer = null;
}, delay);
};
}
function debounce(fn: Function, delay: number = 500) {
let timer: any = null;
return function (...args: any) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, ...args);
timer = null;
}, delay);
};
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
节流
ts
function throttle(fn: Function, delay: number) {
let timer: any = null;
return function (...args: any) {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, ...args);
timer = null;
}, delay);
};
}
function throttle(fn: Function, delay: number) {
let timer: any = null;
return function (...args: any) {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, ...args);
timer = null;
}, delay);
};
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10