下面是网上学来的方法
// 防抖动1
debounce(func, wait) {
const context = this
const args = arguments
if (this.debounceTimeout) clearTimeout(this.debounceTimeout)
this.debounceTimeout = setTimeout(() => {
func.apply(context, args)
}, wait)
}
实际使用会发现,他不能直接立即触发函数,还要等wait的延迟。
下面是自己琢磨的方法,单纯的使用计时来控制函数的触发
// 防抖动2
// startTime默认为null。
首次触发 直接执行函数 并为startTime赋值。
再次触发进入else,计算触发间隔,超过wait时间则执行函数,并更新startTime。
未超过则return。
debounce(func, wait) {
if (!this.startTime) {
this.startTime = Date.now()
console.log('执行函数') // func.apply(context, args)
} else {
this.endTime = Date.now()
if (this.endTime - this.startTime > wait) {
console.log('执行函数) // func.apply(context, args)
this.startTime = Date.now()
this.endTime = null
} else {
return
}
}
}