区分 leading 和 trailing 的关键在于触发时机:设置 leading: true 时,函数在事件触发的瞬间立即执行;设置 trailing: true 时,函数在最后一次触发后等待指定时间再执行。通常通过传入 options 对象来配置这两个参数,默认情况下防抖(debounce)是 trailing 模式,而节流(throttle)则是 leading 模式。

如何配置 debounce 的 leading 和 trailing 选项
在实现防抖函数时,可以通过检查 options.leading 来决定是否在调用开始时立即执行。如果 leading 为真,则在定时器启动前直接调用原函数,并重置定时器以处理后续的 trailing 调用。以下代码展示了完整的防抖实现及测试用例。
function debounce(func, wait, options = {}) {
let timeoutId;
let lastArgs;
let lastThis;
const later = function () {
timeoutId = null;
if (!options.leading && lastArgs) {
func.apply(lastThis, lastArgs);
lastArgs = lastThis = null;
}
};
return function (...args) {
lastArgs = args;
lastThis = this;
if (!timeoutId) {
if (options.leading) {
func.apply(this, args);
}
timeoutId = setTimeout(later, wait);
} else {
clearTimeout(timeoutId);
timeoutId = setTimeout(later, wait);
}
};
}
// 测试 leading: true
const logLeading = debounce(console.log, 300, { leading: true });
logLeading('A'); // 立即输出 A
setTimeout(() => logLeading('B'), 100); // 被忽略
setTimeout(() => logLeading('C'), 400); // 立即输出 C
// 测试 trailing: true (默认)
const logTrailing = debounce(console.log, 300, { trailing: true });
logTrailing('X'); // 被忽略
setTimeout(() => logTrailing('Y'), 100); // 被忽略
setTimeout(() => logTrailing('Z'), 400); // 300ms后输出 Z如何配置 throttle 的 leading 和 trailing 选项
节流函数的核心逻辑是控制单位时间内的执行次数。默认情况下,节流函数在第一次触发时立即执行(leading),并在后续时间内忽略请求。如果需要仅在间隔结束时执行(trailing),则需要在定时器回调中判断是否还有未执行的调用。以下是基于同一输入源的节流实现对比。
你是 TypeScript 项目架构专家,专注于脚手架搭建生产就绪的 Node.js 和前端应用。生成包含现代工具链(pnpm、Vite、Next.js)、类型
function throttle(func, wait, options = {}) {
let timeoutId;
let lastCallTime;
let lastArgs;
let lastThis;
const later = function () {
lastCallTime = Date.now();
timeoutId = null;
if (options.trailing && lastArgs) {
func.apply(lastThis, lastArgs);
lastArgs = lastThis = null;
}
};
return function (...args) {
const now = Date.now();
const remaining = wait - (now - lastCallTime);
lastArgs = args;
lastThis = this;
if (remaining <= 0 || remaining > wait) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
lastCallTime = now;
if (options.leading !== false) {
func.apply(this, args);
}
} else if (!timeoutId && options.trailing !== false) {
timeoutId = setTimeout(later, remaining);
}
};
}
// 测试 leading: true (默认)
const scrollLeading = throttle(console.log, 500, { leading: true });
scrollLeading('Start'); // 立即输出 Start
setTimeout(() => scrollLeading('Middle'), 200); // 被忽略
setTimeout(() => scrollLeading('End'), 600); // 立即输出 End
// 测试 trailing: true
const scrollTrailing = throttle(console.log, 500, { leading: false, trailing: true });
scrollTrailing('Start'); // 被忽略
setTimeout(() => scrollTrailing('Middle'), 200); // 被忽略
setTimeout(() => scrollTrailing('End'), 600); // 500ms后输出 End当 leading 和 trailing 同时为 true 时会发生什么
如果在防抖或节流函数中同时设置 leading: true 和 trailing: true,函数会在触发瞬间执行一次,并在最后一次触发后的等待期结束后再次执行。这种组合常用于需要即时反馈且必须保证最终状态同步的场景,例如搜索框输入时的实时建议与最终提交。
立即学习“Java免费学习笔记(深入)”;

















