小程序添加节流阀

另一个文件中
/**

  • 防抖与节流
  • fn 被调用函数
  • wait 等待时间
  • isDebounce 是否是防抖
    */
    export const throttle = (fn, wait, isDebounce) => {
    let timer
    let lastCall = 0;
    return function () { // 此处不可用箭头函数
    const context = this;
    const args = arguments
    if(isDebounce) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => fn.call(context, ...args), wait)
    } else {
    const curTime = new Date().getTime();
    if (curTime - lastCall > wait) {
    fn.call(context, ...args)
    lastCall = curTime;
    }
    }
    }
    }

在methods的方法后面直接运行节流阀(切记不可用箭头函数())
methods: {
addToCart: throttle(function () {
const { count } = this.data;
this.triggerEvent("addToCart", { count });
}, 300, true) ,
}

原文地址:https://www.cnblogs.com/zgdongyywei/p/14734297.html