封装javascript防抖和节流装饰器,核心在于利用闭包保存定时器或时间戳,并在装饰器函数中返回一个新的包装函数。通过传入配置参数(如`leading`、`trailing`、`maxwait`)来控制触发时机,从而在高频事件回调中实现性能优化。

如何封装支持配置的防抖装饰器
防抖装饰器的实现依赖于一个内部状态来记录最后一次触发的时间或定时器ID。当被装饰的函数被连续调用时,它会重置定时器,只有当调用停止超过指定延迟后,原函数才会执行。这种机制非常适合搜索输入框等场景,避免在用户打字过程中频繁发起请求。

function debounce(fn, options = {}) {
let timer = null;
let lastArgs = null;
let lastThis = null;
const { wait = 300, leading = false, trailing = true } = options;
function debounced(...args) {
lastArgs = args;
lastThis = this;
if (timer) clearTimeout(timer);
if (leading && !timer) {
fn.apply(lastThis, lastArgs);
}
timer = setTimeout(() => {
timer = null;
if (trailing && !leading) {
fn.apply(lastThis, lastArgs);
} else if (leading && lastArgs) {
// Handle case where leading was true but we need to execute on idle
// This logic simplifies for standard trailing behavior
}
}, wait);
}
debounced.cancel = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
return debounced;
}
上述代码定义了一个标准的防抖函数。它接收目标函数`fn`和配置对象`options`。内部使用`timer`变量存储定时器ID。每次调用`debounced`时,先清除旧定时器,然后设置新定时器。如果配置了`leading: true`,则在第一次调用时立即执行;否则,等待定时器超时后执行。此外,还提供了一个`cancel`方法用于手动取消待执行的调用。
如何封装支持最大等待时间的节流装饰器
节流装饰器确保函数在指定时间内只执行一次。与防抖不同,节流更关注于“固定频率”的执行。高级节流还可以支持`maxWait`参数,即无论中间触发多少次,如果在最大等待时间内未执行,则强制执行一次,防止长时间不触发导致的响应滞后。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。

function throttle(fn, options = {}) {
let lastTime = 0;
let timer = null;
let lastArgs = null;
let lastThis = null;
const { wait = 300, leading = true, trailing = true, maxWait = null } = options;
function throttled(...args) {
lastArgs = args;
lastThis = this;
const now = Date.now();
const remaining = wait - (now - lastTime);
if (timer) {
// Already waiting for maxWait or trailing
return;
}
if (lastTime === 0 || remaining {
fn.apply(lastThis, lastArgs);
lastTime = Date.now();
timer = null;
}, remaining);
}
// Handle maxWait
if (maxWait && !timer && lastTime !== 0) {
const elapsed = Date.now() - lastTime;
if (elapsed >= maxWait) {
fn.apply(lastThis, lastArgs);
lastTime = Date.now();
}
}
}
throttled.cancel = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
lastTime = 0;
};
return throttled;
}
该节流实现使用了时间戳对比法。`lastTime`记录上次执行时间。每次调用时计算剩余时间`remaining`。如果处于冷却期且允许尾部执行,则设置定时器。同时检查是否达到`maxWait`,如果达到则强制执行并重置时间。这确保了即使在高频率触发下,函数也能按预期频率执行,不会无限期延迟。
装饰器如何处理this上下文和参数传递
在封装装饰器时,保持原函数的`this`指向和参数列表是至关重要的。JavaScript中的函数可以通过`call`、`apply`或`bind`来改变上下文。在防抖和节流的包装函数中,我们需要捕获当前的`this`和`arguments`(或展开参数),并在最终执行原函数时将其还原。如果不处理这一点,原函数内部访问`this`可能会指向全局对象或`undefined`(严格模式下),导致错误。
在上述代码示例中,`debounced`和`throttled`函数都使用了剩余参数语法`...args`来收集所有传入的参数,并使用`lastThis`变量保存当前的`this`引用。在调用原函数`fn`时,使用`fn.apply(lastThis, lastArgs)`来确保上下文和参数正确传递。这种模式保证了装饰器对原函数的透明性,开发者无需修改原函数即可享受防抖或节流带来的性能提升。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










