防抖和节流有很多人都会分不清楚,下面用一小句话来概括一下,加上代码,快速掌握原理
防抖
防抖就是公交车等人上车,有人上等5s,5s内又有人上再等5s
function debounce (fn, delay = 300){
let timer = null
return function (...args) {
clearTimeout(timer)
timer = setTimeout(()=>{
fn.call(this, ...args)
}, delay);
}
}
debounce(()=> {}, 1000)
2.节流
节流就是公交车固定5分钟一班车
let timer = null
function throttle (fn, delay = 300) {
if(timer == null){
timer = setTimeout(() => {
fn()
clearTimeout(timer)
timer = null
}, delay);
}
}
throttle(()=> {}, 1000)