當一個事件可能被高頻觸發(例如 scroll、resize、mousemove),而處理起來又不便宜時,就需要這兩個工具來節流。
無視一定時間內的所有呼叫,只讓第一次通過。適合觸發頻度高、每次處理又比較重的場合。
var throttle = function (func, threshold, alt) {
var last = Date.now();
threshold = threshold || 100;
return function () {
var now = Date.now();
if (now - last < threshold) {
if (alt) {
alt.apply(this, arguments);
}
return;
}
last = now;
func.apply(this, arguments);
};
};
這裡的 alt 是一個可選的替代回呼:在間隔時間內被呼叫時,改執行 alt 而不是直接丟棄,可以拿來做一些輕量的回饋。
必須在一段間隔內沒有新的呼叫,才真正執行。也就是「等使用者停下來才做」。
var debounce = function (func, threshold, execASAP) {
var timeout = null;
threshold = threshold || 100;
return function () {
var self = this;
var args = arguments;
var delayed = function () {
if (!execASAP) {
func.apply(self, args);
}
timeout = null;
};
if (timeout) {
clearTimeout(timeout);
} else if (execASAP) {
func.apply(self, args);
}
timeout = setTimeout(delayed, threshold);
};
};
execASAP 控制邊沿行為:設為 true 時,在一串呼叫的第一次就立即執行,後續的呼叫只負責重置計時器;設為 false 時則相反,等到寂靜期結束才執行一次。
用電梯來比喻:throttle 是「每分鐘最多開一次門,其間按了不算」;debounce 是「你按住不放就一直不開,等你鬆手後才開」。
因此,捲軸時想讓面板持續更新,用 throttle;搜尋框的即時查詢想等使用者打完再送,用 debounce。
var test = function (wrapper, threshold) {
var log = function () {
console.log(Date.now() - start);
};
var wrapperedFunc = wrapper(log, threshold);
var start = Date.now();
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(wrapperedFunc);
}
while (i > 0) {
var random = Math.random() * 1000;
console.log('index: ' + i);
console.log('random: ' + random);
setTimeout(arr[--i], random);
}
};
test(debounce, 1000);
test(throttle, 1000);
這段測試隨機安排十次呼叫,間隔在 0 到 1 秒之間,藉此觀察兩個 wrapper 的實際觸發時機。跑一次就能直觀感受到:throttle 大約每一秒吐一次結果,debounce 則只在最後一次呼叫後才吐一次。