防抖分为两种:
一种是立即执行:频繁触发事件,第一次触发时执行函数,后面触发不会执行,停止触发,间隔一定时间之后再触发事件,函数才会再次执行
另一种是后执行:频繁触发事件,事件只会在触发事件之后间隔定义的时间,函数才会被执行,而且只会执行最后一次触发的事件。
函数节流
定义:事件触发后,会先执行一次事件函数,执行之后如果在规定时间间隔内再触发事件,将不出触发函数,超过规定的事件间隔后会再次触发一次,如此往复
let timeout = null
let timer = null
let start = 0
//函数防抖(debounce)
export const debounce = (func, delay) => {
if (timeout !== null) clearTimeout(timeout)
timeout = setTimeout(func, delay)
}
//使用
handleMouseOut() {
this.timeTips = {
width: "182px",
display: "none"
};
debounce(() => {
this.timeTips = {
width: "182px",
display: "none"
};
}, 1000);
},
//函数节流(Throttle)
export const Throttle = (func, wait, trailing) => {
let now = new Date()
if ((now - start) >= wait) {
timer && clearTimeout(timer)
timer = null
start = now
return func()
} else if (!timer && trailing) {
timer = setTimeout(() => {
timer = null
return func
}, wait)
}
}