節流和防抖常用與監聽滾動事件,移動事件,窗口改變大小事件,輸入事件等高頻觸發事件,當事件處理函數較爲複雜時,將導致無法實時響應,降低用戶體驗度,影響效率,出現頁面卡頓,假死等現象。
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),
}
...