防抖
function debounce(fn, t){
let flag = null
return function (...args) {
clearTimeout(flag)
flag = setTimeout(() => {
fn.apply(this, args)
}, t)
}
}
节流
- 时间戳实现
function throttle(fn, wait){
let pre = Date.now()
return function(...args){
let now = Date.now()
if(now - pre >= wait){
fn.apply(this, args)
pre = Date.now()
}
}
}
- 定时器实现
function throttle(fn, wait){
let timer = null;
return function(...args){
if(!timer) {
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, wait)
}
}
}