Appearance
防抖和节流
防抖
javascript
function debounce(fun, delay){
let timer
return function(){
if(timer) clearTimeout
let args = arguments
timer = setTimeout(()=>{
fun.apply(this, args)
}, delay)
}
}节流
javascript
function throttle(fun, delay){
let start = 0
return function(){
let now = new Date()
if(now - start > time){
fun.apply(this, arguments)
start = now
}
}
}ts版本
防抖:
typescript
function debounce(func: Function, delay: number) {
let timer: ReturnType<typeof setTimeout>;
return function(this: any, ...args: any[]) {
const context = this;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}节流:
typescript
function throttle(func: Function, delay: number) {
let timer: ReturnType<typeof setTimeout> | null = null;
let lastTime = 0;
return function(this: any, ...args: any[]) {
const context = this;
const now = Date.now();
if (now - lastTime >= delay) {
func.apply(context, args);
lastTime = now;
} else {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
lastTime = Date.now();
}, delay - (now - lastTime));
}
};
}