主要是為了避免在頻繁的操作中導(dǎo)致頁面的卡頓艾杏,因此將短時間內(nèi)多次的操作合并為一次颖低。
const debounce = (func, wait=50) => {
let timer = 0
let f = function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
})
}
return f
}
但是串纺,有時候需要需要立刻執(zhí)行摆霉,因此做一下修改
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
}