节流和防抖常用与监听滚动事件,移动事件,窗口改变大小事件,输入事件等高频触发事件,当事件处理函数较为复杂时,将导致无法实时响应,降低用户体验度,影响效率,出现页面卡顿,假死等现象。
debounce 周期内有新事件触发,清除旧定时器,重置新定时器;这种方法,需要高频的创建定时器。
throttling 周期内有新事件触发时,重置定时器开始时间撮,定时器执行时,判断开始时间撮,若开始时间撮被推后,重新设定延时定时器。
1.定义模块文件并导出防抖函数和节流函数
/**
* 函数防抖 (只执行最后一次点击)
* @param fn
* @param delay
* @returns {Function}
* @constructor
*/
export const Debounce = (fn, t) => {
let delay = t || 500;
let timer;
console.log(fn)
console.log(typeof fn)
return function () {
let args = arguments;
if(timer){
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, delay);
}
};
/**
* 函数节流
* @param fn
* @param interval
* @returns {Function}
* @constructor
*/
export const Throttle = (fn, t) => {
let last;
let timer;
let interval = t || 500;
return function () {
let args = arguments;
let now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn.apply(this, args);
}, interval);
} else {
last = now;
fn.apply(this, args);
}
}
};
2.在组件中导入函数
import {
Debounce,
Throttle
} from '@/common/config/debThr.js';
3.methods中调用
...
methods:{
/*
小提示:不要写成回调函数的形式 this指向改变了
*/
getAliyunData:Throttle(function(){
...
},1000),
}
...