防抖、节流的意义
在一些高频率事件触发的场景下,我们希望对应的事件只执行一次
防抖、节流适用的场景
- 点击事件
- 滚动事件
- 轮播事件
- input模糊匹配
防抖函数的实现
const debounce = (fn, wait) => {
if(typeof fn !== 'function') throw new Error('fn must function')
if(typeof wait === 'undefined') wait = 1000
let timer = null
return function proxy(...args) {
const that = this
clearTimeout(timer)
timer = setTimeout(() => {
fn.call(that,args)
}, wait)
}
}
节流函数的实现
const throttle = (fn,wait) => {
if(typeof fn !== 'function') throw new Error('fn must function')
if(typeof wait === 'undefined') wait = 1000
let previous = 0 // 记录上一次执行的时间
let timer = null
return function proxy(...args) {
const that = this
const now = new Date()
const interval = wait - now + previous
if(interval <= 0) {
// 非高频操作
clearTimeout(timer)
timer = null
fn.call(that, ...args)
previous = new Date()
} else if(!timer) {
timer = setTimeout(() => {
clearTimeout(timer)
timer = null
fn.call(that, ...args)
previous = new Data()
}, interval)
}
}
}