// 节流 (N秒内触发一次)
throttle(fn, interval) {
let last = 0
return function () {
let context = this
let args = arguments
let now = +new Date()
if ((now - last) > interval) {
last = now
fn.apply(context, args)
}
}
},
// 防抖(最后N秒后触发)
debounce(fn, delay) {
let timer = null
return function () {
let context = this
let args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(context, args)
}, delay)
}
},
// 整合防抖和节流
betterDebounce(fn, delay) {
let last = 0
let timer = null
return function () {
let context = this
let args = arguments
let now = +new Date();
if ((now -last) < delay) {
clearTimeout(timer)
timer = setTimeout( () => {
fn.apply(context, args)
last = now
}, delay)
} else {
last = now;
fn.apply(context, args)
}
}
},