防抖和节流
防抖
事件触发以后等待一段时间再执行,在等待的时间内再次出发,则重新计时.等待时间结束以后执行代码,目的是保证事件只执行一次,多次触发时最后一次生效
/**
* 防抖函数 (Debounce)
* @param {Function} func - 需要防抖的函数
* @param {number} wait - 等待时间(毫秒)
* @param {boolean} immediate - 是否立即执行首次触发
* @returns {Function} - 包装后的防抖函数
*/
function debounce(func, wait = 300, immediate = false) {
let timer = null;
return function(...args) {
const context = this;
// 若已有计时器则清除,实现「重新计时」
if (timer) clearTimeout(timer);
// ----- 立即执行逻辑 -----
if (immediate) {
// 如果计时器不存在,说明可以立即执行
const callNow = !timer;
// 启动新的计时器 (wait 后清空 timer)
timer = setTimeout(() => {
timer = null;
}, wait);
// 立即执行函数
if (callNow) func.apply(context, args);
}
// ----- 延迟执行逻辑 -----
else {
timer = setTimeout(() => {
func.apply(context, args);
}, wait);
}
};
}节流
事件触发以后,在执行完以前,拦截再次触发的事件,直到第一次触发的事件返回结果. 多次触发只执行第一次
/**
* 节流函数 (Throttle) - 时间戳 + 定时器组合实现
* @param {Function} func - 需要节流的函数
* @param {number} wait - 间隔时间(毫秒)
* @param {boolean} leading - 是否执行首次触发
* @param {boolean} trailing - 是否执行最后一次触发
* @returns {Function} - 包装后的节流函数
*/
function throttle(func, wait = 300, leading = true, trailing = true) {
let timer = null;
let previous = 0;
return function(...args) {
const context = this;
const now = Date.now();
// ----- 首执行控制 -----
if (!previous && leading === false) previous = now;
// 剩余时间计算
const remaining = wait - (now - previous);
// 剩余时间 ≤0 或 调整了系统时间 (remaining > wait)
if (remaining <= 0 || remaining > wait) {
// 清除之前的定时器
if (timer) {
clearTimeout(timer);
timer = null;
}
// 更新执行时间戳
previous = now;
// 执行函数
func.apply(context, args);
}
// ----- 尾执行控制 -----
else if (!timer && trailing === true) {
timer = setTimeout(() => {
// 恢复 previous 为 leading=false 时不记录时间戳
previous = leading === false ? 0 : Date.now();
timer = null;
func.apply(context, args);
}, remaining);
}
};
}Lodash
lodash中定义了防抖和节流的方法,调用方法会返回一个实现防抖或节流的fun,执行这个fun
防抖
_.debounce(func, [wait=0], [options=])创建一个 debounced(防抖动)函数,该函数会从上一次被调用后,延迟 wait 毫秒后调用 func 方法。 debounced(防抖动)函数提供一个 cancel 方法取消延迟的函数调用以及 flush 方法立即调用。 可以提供一个 options(选项) 对象决定如何调用 func 方法,options.leading 与|或 options.trailing 决定延迟前后如何触发(注:是 先调用后等待 还是 先等待后调用)。 func 调用时会传入最后一次提供给 debounced(防抖动)函数 的参数。 后续调用的 debounced(防抖动)函数返回是最后一次 func 调用的结果。
参数
func(Function): 要防抖动的函数。[wait=0](number): 需要延迟的毫秒数。[options=](Object): 选项对象。[options.leading=false](boolean): 指定在延迟开始前调用。[options.maxWait](number): 设置func允许被延迟的最大值。[options.trailing=true](boolean): 指定在延迟结束后调用。
示例
// 避免窗口在变动时出现昂贵的计算开销。
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
// 当点击时 `sendMail` 随后就被调用。
jQuery(element).on('click', _.debounce(sendMail, 300, {
'leading': true,
'trailing': false
}));
// 确保 `batchLog` 调用1次之后,1秒内会被触发。
var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
// 取消一个 trailing 的防抖动调用
jQuery(window).on('popstate', debounced.cancel);
节流
_.throttle(func, [wait=0], [options=])创建一个节流函数,在 wait 秒内最多执行 func 一次的函数。 该函数提供一个 cancel 方法取消延迟的函数调用以及 flush 方法立即调用。 可以提供一个 options 对象决定如何调用 func 方法, options.leading 与|或 options.trailing 决定 wait 前后如何触发。 func 会传入最后一次传入的参数给这个函数。 随后调用的函数返回是最后一次 func 调用的结果。
参数
func(Function): 要节流的函数。[wait=0](number): 需要节流的毫秒。[options=](Object): 选项对象。[options.leading=true](boolean): 指定调用在节流开始前。[options.trailing=true](boolean): 指定调用在节流结束后。
示例
// 避免在滚动时过分的更新定位
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
// 点击后就调用 `renewToken`,但5分钟内超过1次。
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
// 取消一个 trailing 的节流调用。
jQuery(window).on('popstate', throttled.cancel);