防抖和节流都是防止某一时间频繁触发,但是原理却不一样。
防抖是将多次执行变为只执行一次,节流是将多次执行变为每隔一段时间执行。
防抖:
function debounce (fn, delay) {
let timer = null
return function () {
if(timer) clearTimeout(timer)
timer = setTimeout(()=>{
fn.call(this)
},delay)
}
}
节流:
时间戳实现
function throttle (fn, wait) {
let start = 0
return function (){
let now = new Date.getTime()
if(now - start < wait) return
fn()
start = now
}
}
定时器实现
function throttle(fn, wait){
let lock = true
return function (){
if(lock){
lock = false
setTimeout(()=>{
lock = true
fn()
},wait)
}
}
}