节流函数的两种写法

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

应用场景

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

手写实现

时间戳

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
8
9
10
11
12
13
14
15
16
17
18
19
function throttle(func, delay) {
let timer = null; // 用于保存定时器的引用

return function (...args) {
const context = this; // 保存当前上下文

// 如果定时器已经存在,说明上次的定时器还没有执行完
if (timer) return;

// 设置一个新的定时器
timer = setTimeout(() => {
// 执行传入的函数
func.apply(context, args);

// 清除定时器
timer = null;
}, delay);
};
}

通过手写,可以更好地理解它们的原理和应用场景。在实际开发中,请直接使用 Lodash 等工具库提供的 throttle 方法。

1
_.throttle(func, [wait=0], [options=])