节流


节流(Throttle)

节流的核心思想是:在一定时间间隔内,无论事件触发多少次,只执行一次函数。

应用场景

  • 滚动事件(每隔一段时间检查滚动位置)。
  • 按钮点击(防止用户快速多次点击)。

手写实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function throttle(func, delay) {
let lastTime = 0; // 记录上次执行的时间

return function (...args) {
const context = this; // 保存当前上下文
const now = Date.now(); // 获取当前时间

// 如果距离上次执行的时间大于设定的延迟,则执行函数
if (now - lastTime >= delay) {
func.apply(context, args);
lastTime = now; // 更新上次执行时间
}
};
}

使用示例

1
2
3
4
5
6
7
function onScroll() {
console.log('Scroll event triggered');
}

const throttledScroll = throttle(onScroll, 300);

window.addEventListener('scroll', throttledScroll);