VUE封装防抖和节流

防抖分为两种:
一种是立即执行:频繁触发事件,第一次触发时执行函数,后面触发不会执行,停止触发,间隔一定时间之后再触发事件,函数才会再次执行
另一种是后执行:频繁触发事件,事件只会在触发事件之后间隔定义的时间,函数才会被执行,而且只会执行最后一次触发的事件。

函数节流
定义:事件触发后,会先执行一次事件函数,执行之后如果在规定时间间隔内再触发事件,将不出触发函数,超过规定的事件间隔后会再次触发一次,如此往复

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)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值