1 export class Debounced {
2
3 /**
4 *
5 * @param fn 要执行的函数
6 * @param awit 时间
7 * @param immediate 是否在触发事件后 在时间段n开始,立即执行,否则是时间段n结束,才执行
8 */
9 static use(fn:Function,awit:number=1000,immediate:boolean=false){
10 let timer:NodeJS.Timeout|null
11 return (...args:any)=>{
12 if(timer) clearInterval(timer)
13 if(immediate){
14 if(!timer) fn.apply(this,args);
15 timer = setTimeout(function(){//n 秒内 多次触发事件,重新计算.timeer
16 timer = null;//n 秒内没有触发事件 timeer 设置为null,保证了n 秒后能重新触发事件 flag = true = !timmer
17 },awit)
18 }else{
19 timer = setTimeout(()=>{ fn.apply(this,args)},awit)
20 }
21 }
22 }
23
24 }
export class Throttle{
/**
*
* @param fn
* @param awit
* @param immediate true 是启用时间戳版,false 是启用定时器版,作用一样
*/
static use(fn:Function,awit:number=1000,immediate:boolean=true){
//时间戳
if(immediate){
let prevTime = 0;
return (...args:any)=>{
let nowTime = Date.now();
if(nowTime-prevTime>=awit){
fn.apply(this,args)
prevTime=nowTime
}
}
}else{
//定时器
let timer: NodeJS.Timeout|null;
return (...args:any)=>{
if(!timer){
fn.apply(this,args)
timer = setTimeout(() => {
timer&&clearTimeout(timer)
timer= null
}, awit);
}
}
}
}
}