节流
节流:减少触发的次数,单位时间内执行相应函数1次
function throttle1(func, interval = 1000) {
let startTime = 0
return function (...args) {
const nowTime = new Date().getTime()
const waitTime = interval - (nowTime - startTime)
if (waitTime <= 0) {
func.apply(this, args)
startTime = nowTime
}
}
}
function throttle2(func, delay = 500) {
let timer = null
return function () {
if (timer) {
return
}
timer = setTimeout(() => {
func.apply(this, arguments)
}, delay);
}
}
防抖
防抖:
等待时间小于delay内不断触发,前面触发的都取消。
等待时间大于等于delay后才执行相应的函数
function debounce(func, delay = 500) {
let timer = null
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, delay);
}
}