主要是为了避免在频繁的操作中导致页面的卡顿,因此将短时间内多次的操作合并为一次。
const debounce = (func, wait=50) => {
let timer = 0
let f = function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
})
}
return f
}
但是,有时候需要需要立刻执行,因此做一下修改
const debounce = (func, wait=50, immediate=true) => {
let timer = 0
let context = null
let args = null
const later = () => {
setTimeout(() => {
timer = null
if (!immediate) {
func.apply(context, args)
context = null
args = null
}
}, wait)
}
let f = function (...params) {
if (timer) {
clearTimeout(timer)
timer = later()
} else {
timer = later()
if (immediate) {
func.apply(context, args)
} else {
context = this
args = params
}
}
}
return f
}