1. 定義
/**
* @param {Function} [fn] [執(zhí)行的函數]
* @param {Number} [delay] [延遲毫秒數]
* @param {Boolean} [isDebounce] [執(zhí)行防抖還是節(jié)流]
*
* @return {Function} [返回匿名函數]
*/
function throttle(fn, delay, isDebounce) {
let timer;
let lastCall = 0;
return function(...args) {
if (isDebounce) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn(...args);
}, delay);
} else {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
fn(...args);
}
}
}
2. 使用
const doAction = throttle((x,y)=>{console.log(x,y)},100,true)
window.onresize = () => {
doAction(1,2);
};
3. 防抖 與 節(jié)流的區(qū)別
防抖:當前時間段內只有一個處理函數
節(jié)流:過一段時間就觸發(fā)一個處理函數
4. 備注
... (三個點): 多數情況下停做,用于擴展嫡霞,也叫擴展運算符,也有聚合功能包斑,本文中...args就是聚合功能摘昌,將外面?zhèn)魅氲膮稻酆蠟?strong>args數組斥杜。
對...args有疑問虱颗,請看here