今天我们来读lodash的节流防抖部分代码。
节流和防抖,是限制函数高频执行的一种手段。它们概念的区别在于,防抖合并多次函数执行为一次
;节流是在一定的时间内函数只执行一次
。具体的区别可以参考lodash
官网推荐的这篇文章。
虽然明细了概念的区别,但是在lodash
源码中,这两个方式其实是一个实现。lodash
中_.debounce
对应防抖,_.throttle
则对应节流。我们先来看一下throttle
部分的代码。
/**
* @param {Function} func: 要节流的函数。
* @param {Number} wait 需要节流的毫秒
* @param {Object} options 选项对象
* [options.leading=true] (boolean): 指定调用在节流开始前。
* [options.trailing=true] (boolean): 指定调用在节流结束后。
* @returns {Function} Returns the new throttled function.
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
// 非函数抛错
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
// options 为对象时,进行 leading 和 trailing 的参数设置
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
});
}
throttle
函数非常的简单,进行默认值选项leading
和trailing
的设置。然后对入参类型进行检测,接着直接返回调用debounce
函数的内容。尽管lodash
官方上面画了不少篇幅来介绍节流防抖的感念区别,其实防抖
函数就是直接使用节流
函数的逻辑来实现的。
让我们把视线转到debounce
函数。debounce
的配置设置是一个高阶函数,放入你需要防抖的函数和调用配置,返回处理好的函数。先来看一下函数的入参以及入参处理。
/**
* @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.
*/
function debounce(func, wait