防抖:在规定的间隔时间里,只执行最后一次操作,中途有影响,就重新计时。
例:电梯开关门
const debounce = (func, wait = 100) => {
let timer = 0
return function (...args) {
if (timer) {
console.log("有人进来,重新计时")
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
节流:在规定的间隔时间里,只执行一次操作,中途有影响,不停止计时。
例:搜索框
const throttle = (func, wait = 50) => {
let lastTime = 0
return function (...args) {
let now = +new Date()
if (now - lastTime > wait) {
lastTime = now
func.apply(this, args)
}
}
}