1. 什么是函數去抖 & 函數節流
讓某個函數在一定 事件間隔條件(去抖debounce) 或 時間間隔條件(節流throttle) 下才會去執行,避免快速多次執行函數(操作DOM,加載資源等等)給內存帶來大量的消耗從而一定程度上降低性能問題。
debounce: 當調用動作n毫秒后,才會執行該動作,若在這n毫秒內又調用此動作則將重新計算執行時間。
throttle:預先設定一個執行周期,當調用動作的時刻大于等于執行周期則執行該動作,然后進入下一個新周期。
debounce使用場景
-
scroll
事件(資源的加載) -
mousemove
事件(拖拽) -
resize
事件(響應式布局樣式) -
keyup
事件(輸入框文字停止打字后才進行校驗)
debounce電梯:
假設你正在準備乘坐電梯,并且電梯門準備關上然后上升的時候,你的同事來了,出于禮貌,我們需要停止電梯的關閉,讓同事進入.假設源源不斷的有同事進來的話,電梯就需要處于一種待機的狀態,一直等待人員的進入,直到沒有新的同事進入或者說電梯滿了,這個時候,電梯才能運行.另外,同事的進入需要在電梯門的關閉之前,否則的話,就只能等下一趟了。換成圖示我們可以這么理解:
throttle使用場景
-
click
事件(不停快速點擊按鈕,減少觸發頻次) -
scroll
事件(返回頂部按鈕出現\隱藏事件觸發) -
keyup
事件(輸入框文字與顯示欄內容復制同步) - 減少發送ajax請求,降低請求頻率
throttle電梯:
throttle電梯不想debounce電梯一樣會無限的等待,而是我們設定一個時間,例如10s,那么10s內,其他的人可以不斷的進入電梯,但是,一旦10s過去了,那么無論如何,電梯都會進入運行的狀態。換成圖示,我們可以這么理解:
2. 實現方法&應用
首先是自己寫的各自簡易的實現,然后對比理解Lodash實現的復雜版本。看完你會發現節流本質上是去抖的一種特殊實現。
a. 簡單實現
debounce
.html
<button id="btn">click</button>
<div id="display"></div>
.js
/**
* 防反跳。fn函數在最后一次調用時刻的delay毫秒之后執行!
* @param fn 執行函數
* @param delay 時間間隔
* @param isImmediate 為true,debounce會在delay時間間隔的開始時立即調用這個函數
* @returns {Function}
*/
function debounce(fn, delay, isImmediate) {
var timer = null; //初始化timer,作為計時清除依據
return function() {
var context = this; //獲取函數所在作用域this
var args = arguments; //取得傳入參數
clearTimeout(timer);
if(isImmediate && timer === null) {
//時間間隔外立即執行
fn.apply(context,args);
timer = 0;
return;
}
timer = setTimeout(function() {
fn.apply(context,args);
timer = null;
}, delay);
}
}
/* 方法執行e.g. */
var btn = document.getElementById('btn');
var el = document.getElementById('display');
var init = 0;
btn.addEventListener('click', debounce(function() {
init++;
el.innerText = init;
}, 1000,true));
說明:
這里實現了一個有去抖功能的計數器。該函數接收三個參數,分別是要執行的函數fn
、事件完成周期時間間隔delay
(即事件間隔多少時間內不再重復觸發)以及是否在觸發周期內立即執行isImmediate
。需要注意的是要給執行函數綁定一個調用函數的上下文以及對應傳入的參數。示例中對click
事件進行了去抖,間隔時間為1000毫秒,為立即觸發方式,當不停點擊按鈕時,第一次為立即觸發,之后直到最后一次點擊事件結束間隔delay
秒后開始執行加1操作。
? Demo
throttle
.html
(同上)
.js
/**
* 創建并返回一個像節流閥一樣的函數,當重復調用函數的時候,最多每隔delay毫秒調用一次該函數
* @param fn 執行函數
* @param delay 時間間隔
* @returns {Function}
*/
function throttle(fn, delay) {
var timer = null;
var timeStamp = new Date();
return function() {
var context = this; //獲取函數所在作用域this
var args = arguments; //取得傳入參數
if(new Date()-timeStamp>delay){
timeStamp = new Date();
timer = setTimeout(function(){
fn.apply(context,args);
},delay);
}
}
}
/* 方法執行 */
var btn = document.getElementById('btn');
var el = document.getElementById('display');
var init = 0;
btn.addEventListener('click', throttle(function() {
init++;
el.innerText = init;
}, 1000));
說明:
這里實現了一個簡易的有去節流功能的計數器。該函數接收兩個參數,分別是要執行的函數fn
、事件完成周期時間間隔delay
(即事件間隔多少時間內不再重復觸發)。需要注意的是要給執行函數綁定一個調用函數的上下文以及對應傳入的參數,以及在閉包外層的timeStamp時間記錄戳,用于判斷事件的時間間隔。示例中對click
事件進行了節流,間隔時間為1000毫秒,不停點擊按鈕,計數器會間隔1秒時間進行加1操作。
缺點:
沒有控制事件的頭尾選項,即沒有控制是否在連續事件的一開始及最終位置是否需要執行。(參考underscore彌補)
? Demo
b. 附:Lodash實現
debounce
var isObject = require('./isObject'),
now = require('./now'),
toNumber = require('./toNumber');
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
result = wait - timeSinceLastCall;
return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
module.exports = debounce;
throttle
var debounce = require('./debounce'),
isObject = require('./isObject');
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}
module.exports = throttle;
c. 附:Underscore實現
debounce
/**
* 防反跳。func函數在最后一次調用時刻的wait毫秒之后執行!
* @param func 執行函數
* @param wait 時間間隔
* @param immediate 為true,debounce會在wai 時間間隔的開始調用這個函數
* @returns {Function}
*/
function debounce(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = new Date().getTime() - timestamp; // timestamp會實時更新
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = new Date().getTime();
var callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
}
throttle
/**
* 創建并返回一個像節流閥一樣的函數,當重復調用函數的時候,最多每隔 wait毫秒調用一次該函數
* @param func 執行函數
* @param wait 時間間隔
* @param options 如果你想禁用第一次首先執行的話,傳遞{leading: false},
* 如果你想禁用最后一次執行的話,傳遞{trailing: false}
* @returns {Function}
*/
function throttle(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : new Date().getTime();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = new Date().getTime();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
[參考]