// 防抖
function debounce(fn,delay){
let timer = null //借助闭包
return function() { if(timer){
clearTimeout(timer)
}
timer = setTimeout(fn,delay) // 简化写法
}
}
// 节流
function throttle(fn,delay){ let valid = true
return function() { if(!valid){ //休息时间 暂不接客
return false
} // 工作时间,执行函数并且在间隔期内把状态位设为无效
valid = false
setTimeout(() => {
fn()
valid = true;
}, delay)
}
}
js防抖与节流
最新推荐文章于 2024-01-17 19:06:42 发布