普通使用:
/**
* @param { fn } ---->执行的函数
* @param { debounce } ---->特定时间内防止重复点击 默认500毫秒
* @description
*/
let timer, bool;
function throttle(fn, debounce = 500) {
if (!bool) {
bool = true;
typeof fn === 'function' && fn();
timer = setTimeout(() => {
bool = false;
clearTimeout(timer)
}, debounce);
}
};
//使用:
function click(){
throttle(()=> {
console.log("有本事连续点击我啊")
}, 1000);
}
//作为js模块:
let timer, bool;
function throttle(fn, debounce = 500, immediate = true) {
if (!bool) {
bool = true;
typeof fn === 'function' && fn();
timer = setTimeout(() => {
bool = false;
clearTimeout(timer)
}, debounce);
}
};
export default throttle
//ts
export function throttle(fn:(...args:any []) => any,delay:number){
let timer:ReturnType<typeof setTimeout> | null = null,last:number = 0;
return function<T>(this:(...args:any []) => any,...args:Array<T>) {
let now = +new Date();
if(last && now < last + delay){
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn.apply(this,args);
},delay);
}else{
last = now;
fn.apply(this,args);
}
}
}
评论