防抖与节流的羁绊
防抖
let timer = null
function debounce (fn, delay = 1000){
if(timer != null){
clearTimeout(timer)
timer = null
}
timer = setTimeout(fn, delay)
}
const addCount = () => debounce(()=> {
...函数代码
}, 1500)
节流
let timer = null
const throttle =(fn, delay = 300)=> {
if(timer == null){
timer = setTimeout(() => {
fn()
clearTimeout(timer)
timer = null
}, delay);
}
}
const addCount = () => throttle(()=> {
...函数代码
},1000)
-
防抖指:一定时间内多次触发产生替换效果,即只有最后一次会触发
-
节流指:一定时间内只会触发一次,结束后方可再次触发