节流是在指定时间间隔内最多执行一次函数,通过锁定状态和定时器控制执行频率;支持leading和trailing选项;可用requestAnimationFrame实现更平滑的视觉更新;需注意清除监听器、避免闭包引用大对象及区分防抖。

节流(Throttle)是控制高频事件(如 scroll、resize)执行频率的常用手段,核心思想是:**在指定时间间隔内,最多只执行一次函数**。对滚动事件而言,它能显著减少回调调用次数,避免页面卡顿或重复计算。
节流的基本原理
节流函数内部维护一个“锁定状态”和一个定时器。当事件触发时:
- 若处于锁定中,直接忽略;
- 若未锁定,则立即执行目标函数,并启动定时器;
- 定时器到期后才解除锁定,允许下一次执行。
这保证了函数执行的最小时间间隔,比如每 100ms 最多执行一次,无论用户滚动多快。
手写一个简单可靠的节流函数
以下是一个无依赖、支持 leading(首次立即执行)和 trailing(结尾补一次)的节流实现:
function throttle(func, delay, options = {}) {
let lastCall = 0;
let timeoutId = null;
const { leading = true, trailing = false } = options;
<p>return function throttled(...args) {
const now = Date.now();
const elapsed = now - lastCall;</p><pre class="brush:php;toolbar:false;">if (elapsed > delay) {
if (leading && timeoutId === null) {
func.apply(this, args);
}
lastCall = now;
clearTimeout(timeoutId);
timeoutId = null;
return;
}
if (!timeoutId && trailing) {
timeoutId = setTimeout(() => {
func.apply(this, args);
timeoutId = null;
lastCall = Date.now();
}, delay - elapsed);
}
}; }
使用示例:
const handleScroll = () => {
console.log('滚动位置:', window.pageYOffset);
};
<p>window.addEventListener('scroll', throttle(handleScroll, 100, { leading: true, trailing: false }));</p>
✅ 推荐默认开启 leading: true(首次滚动立刻响应),关闭 trailing(避免松开滚动后额外触发)。
用 requestAnimationFrame 实现更平滑的节流
对于仅需“视觉反馈”或“位置更新”的场景(如吸顶导航、视差滚动),requestAnimationFrame 是比定时器更优的选择——它天然与浏览器刷新节奏同步(约每 16ms 一次),且在页面不可见时自动暂停。
function rafThrottle(func) {
let pending = false;
return function (...args) {
if (!pending) {
pending = true;
requestAnimationFrame(() => {
func.apply(this, args);
pending = false;
});
}
};
}
<p>window.addEventListener('scroll', rafThrottle(() => {
// 每帧最多执行一次,适合 DOM 更新类操作
document.body.style.backgroundColor = window.pageYOffset > 100 ? '#f0f0f0' : '#fff';
}));</p>
实际开发中的关键注意点
使用节流处理滚动事件时,需留意这些细节:
-
别忘了清除监听器:组件卸载或页面跳转前,调用
removeEventListener,否则可能引发内存泄漏; - 避免闭包中引用大对象:节流函数会延长回调生命周期,防止意外持有 DOM 节点或大型数据;
- 区分节流与防抖:节流保频率,防抖保最终结果(如搜索框输入);滚动场景绝大多数用节流;
-
移动端慎用
scroll事件:iOS Safari 中原生滚动可能不触发,建议用touchmove+getBoundingClientRect或监听容器 scroll(如使用overflow: auto的 div)。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











