今天我们来读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, options)

本文深入探讨lodash库中节流和防抖的实现代码。通过分析函数逻辑,解释如何通过配置参数实现防抖和节流功能。文章详细阐述了函数的各个部分,包括参数处理、时间戳检查、执行条件判断等,展示了lodash中如何优雅地处理高频率函数调用限制。
最低0.47元/天 解锁文章
2050

被折叠的 条评论
为什么被折叠?



