vue中防抖节流

项目中经常遇到用户连续点击按钮或者连续输入内容的情况,可以采用节流,防抖的思想进行优化处理

//函数防抖  
Vue.prototype.$debounce = function(fn, delay) {  
  let timer = null;  // 记录上一次的延时器  
    let time = delay || 200;  
    return function() {  
        let args = arguments;  
        let that = this;  
        clearTimeout(timer); // 清除上一次延时器  
        timer = setTimeout(function() {  
            fn.apply(that,args)  
        }, time);  
    }
};  

 eg: this.$debounce(() => {}, 3000);
 
//函数节流  
Vue.prototype.$throttle = (function() {  
    let lastTime;  
    let timer;  
    return function(fn,delay) {  
        let time = delay || 3000;
        let nowTime = Date.now(); // 记录当前函数触发的时间   
        if (lastTime && nowTime - lastTime < time) {  
            clearTimeout(timer);  
        }else{  
            lastTime = nowTime;  
            fn.apply(this);  
        }  
    }  
})();

eg: this.$throttle(() => {}, 3000);

你可能感兴趣的:(前端,vue.js)