理解throttle debounce
- 比較
二者本質(zhì):都是限制頻繁觸發(fā)
二者區(qū)別:
throttle: 節(jié)流閥,保證多少ms內(nèi)只執(zhí)行一次。
debounce: 去抖,保證多少ms內(nèi)不再被觸發(fā)時(shí)就會執(zhí)行一次。 - 類比電梯策略理解:
throttle:第一個人進(jìn)來后15s運(yùn)送一次,不等待。
debounde:第一個人進(jìn)來15s后運(yùn)送一次,假設(shè)15s內(nèi)又有人進(jìn)來,重新計(jì)時(shí),一直到15s內(nèi)不再有人進(jìn)來則運(yùn)送一次 - 一秒理解 throttle debounce:http://demo.nimius.net/debounce_throttle/
throttle debounce 實(shí)現(xiàn)
以throttle-debounce 包代碼解析:
debounce.js:
var throttle = require('./throttle');
module.exports = function ( delay, atBegin, callback ) {
return callback === undefined ? throttle(delay, atBegin, false) : throttle(delay, callback, atBegin !== false);
};
throttle.js:
module.exports = function ( delay, noTrailing, callback, debounceMode ) {
var timeoutID;
// Keep track of the last time `callback` was executed.
var lastExec = 0;
if ( typeof noTrailing !== 'boolean' ) {
debounceMode = callback;
callback = noTrailing;
noTrailing = undefined;
}
function wrapper () {
var self = this;
var elapsed = Number(new Date()) - lastExec;
var args = arguments;
// Execute `callback` and update the `lastExec` timestamp.
function exec () {
lastExec = Number(new Date());
callback.apply(self, args);
}
function clear () {
timeoutID = undefined;
}
if ( debounceMode && !timeoutID ) {
exec();
}
if ( timeoutID ) {
clearTimeout(timeoutID);
}
if ( debounceMode === undefined && elapsed > delay ) {
// throttle時(shí),根據(jù)時(shí)間戳之差是否大于delay決定是否執(zhí)行回調(diào)
exec();
} else if ( noTrailing !== true ) {
// debounce時(shí),setTimeout延遲執(zhí)行回調(diào)
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
}
}
return wrapper;
};
應(yīng)用
shop.js: // 輸入關(guān)鍵字查詢門店
import { throttle, debounce } from 'throttle-debounce';
...
debounce(200, async(val) => { await this.getShopList(val); });
...
還可以參考underscore, lodash 中throttle, debounce的實(shí)現(xiàn),做了更多的兼容和考慮。
throttle debounce 應(yīng)用場景
throttle:
監(jiān)聽resize事件做一些DOM元素的定位更改;
監(jiān)聽scroll 事件判斷上拉時(shí)是否要加載數(shù)據(jù)
debounce:
搜索框輸入發(fā)送ajax請求,監(jiān)聽onchange or keyup 事件進(jìn)行查詢;
Reference
1.https://github.com/lishengzxc/bblog/issues/7
2.http://m.itdecent.cn/p/fb08b7ef31de