项目中经常遇到用户连续点击按钮或者连续输入内容的情况,可以采用节流,防抖的思想进行优化处理
//函数防抖
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);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。