防抖
function debounce(fn, delay, immediate = true) {
let timer //借助闭包
return function() {
if(timer) clearTimeout(timer)
if(immediate) {
let callNow = !timer
timer = setTimeout(() => {
timer = null
}, delay)
if(callNow) fn()
}else{
timer = setTimeout(() => {
fn()
timer = null
}, delay) // 简化写法
}
}
}
节流
function throttle(fn, delay, immediate = true) {
let previous = 0
return function () {
if(immediate){
let now = Date.now()
if(now - previous > delay){
fn()
previous = now
}
}else{
if(!previous){
previous = setTimeout(() => {
fn()
previous = 0
}, delay)
}
}
}
}