第66章 防抖与节流
第66章:防抖与节流——实现简单的事件节流函数
案例题目
在TypeScript中实现一个通用的节流函数,控制高频触发的事件(如滚动、输入、resize)按固定时间间隔执行,并保留正确的this上下文与参数类型。
设计思路
节流的核心是“在一段时间内只执行一次”。使用时间戳对比或定时器锁定:记录上次执行时间,当前时间与上次时间差超过阈值才执行,否则延迟到剩余时间结束后执行。为保留类型安全,使用泛型约束函数签名,并正确处理this类型。
核心代码
// 节流函数:确保fn在wait毫秒内最多执行一次
function throttle<T extends (...args: any[]) => void>(
fn: T,
wait: number
): (...args: Parameters<T>) => void {
let lastTime = 0;
let timer: ReturnType<typeof setTimeout> | null = null;
return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
const now = Date.now();
const remaining = wait - (now - lastTime);
const context = this;
if (remaining <= 0) {
// 时间已到,立即执行
if (timer) {
clearTimeout(timer);
timer = null;
}
lastTime = now;
fn.apply(context, args);
} else if (!timer) {
// 设置定时器,在剩余时间后执行
timer = setTimeout(() => {
lastTime = Date.now();
timer = null;
fn.apply(context, args);
}, remaining);
}
};
}
// 使用示例:节流滚动事件
const logScroll = throttle(() => {
console.log("滚动位置:", window.scrollY);
}, 1000);
window.addEventListener("scroll", logScroll);
运行结果与验证
快速滚动页面时,控制台每秒最多输出一次“滚动位置”日志,不会频繁触发。
测试建议
模拟快速调用:
const test = throttle((n: number) => console.log(n), 100);
连续调用test(1), test(2), test(3),观察输出只会出现1或3,且间隔100ms。
提示:使用
Date.now()计算时间差,比固定计数器更精确;定时器方式可避免最后一次调用被丢弃。注意:若
wait传入0或负数,函数会退化为立即执行模式,可能失去节流意义,建议调用前校验参数。成功要点:节流函数完美保留this指向和参数类型,泛型设计让任意函数签名都能安全复用。
注意事项
此实现为“时间戳+定时器”组合模式,兼顾首次立即执行和末尾补执行。若只需首尾之一,可简化逻辑。真实项目中考虑使用requestAnimationFrame优化滚动场景。