防抖,举个例子就是一个输入框,你输入一个字,如果没写防抖就会调用一下后端的接口进行一次查询,导致接口会调用频繁,服务器压力变大,防抖的作用就是,等你在2秒(假设)内你无法去重复的去调用接口,如果你这2秒内又去输入了文字,那么这个定时器再次重置,再得重新等2秒才能调用接口,这一措施就是等待用户去把内容一次性输入完成再调用接口的意思,同时降低接口的调用频率也缓解服务器压力
方法如下
//第一个参数 传入的方法,第二参数 等待的时间
const antiShakePackag = (fun = (e: object) => {}, delay = 1000) => {
let times: number | null = null;
return (e: object) => {
if (times) {
clearTimeout(times);
}
times = Number(
setTimeout(() => {
fun(e);
//防止内存泄漏,垃圾回收机制没有回收
times = null;
}, delay)
);
};
};
节流
就是防止用户多次频繁的点击按钮,调用接口而做的一个措施,也是为了降低接口的调用频率,缓解服务器压力
//节流
//第一个参数 成功的方法
//第二个参数 失败的方法
//第三个参数 等待的时间
const throttlingPackage = (
success = () => {},
fail = () => {},
delay: number = 1000
) => {
let flag: boolean = true;
let timer: number | null | any = null;
return () => {
if (flag) {
clearTimeout(timer);
flag = false;
//执行代码
success();
//定时器
timer = Number(
setTimeout(() => {
flag = true;
timer = null;
}, delay)
);
} else {
fail();
}
};
};
如果不走方法封装,直接在页面调用,vue的话是可以直接使用的
react的话 timer 需要使用钩子函数,不然无法清除定时器
如下
const timer = useRef()
具体例子
//第一个参数 传入的方法,第二参数 等待的时间
let times: number | null = useRef();
const antiShakePackag = (fun = (e: object) => {}, delay = 1000) => {
return (e: object) => {
if (times) {
clearTimeout(times);
}
times = Number(
setTimeout(() => {
fun(e);
//防止内存泄漏,垃圾回收机制没有回收
times = null;
}, delay)
);
};
};