节流函数(Throttle)
const throttle = (func, delay) => {
let lastCall = 0;
return (...args) => {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
return func(...args);
};
};
-
let lastCall = 0
记录上次执行函数的时间。 -
const now = new Date().getTime()
获取当前时间戳(毫秒)。 -
if (now - lastCall < delay)
判断当前时间与上次调用时间的差是否小于delay
,如果小于,则跳过执行。 -
lastCall = now
更新lastCall
,保证下一次的节流计算准确。 -
return func(...args)
执行传入的func
,并传递所有参数。
功能:
- 限制函数的执行频率,确保在一定时间(
delay
)内最多执行一次。 - 使用时间戳(
lastCall
)判断是否满足时间间隔。
用途:
- 用于优化滚动监听,减少性能开销。
防抖函数(Debounce)
const debounce = (func, delay) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func(...args), delay);
};
};
-
let timeoutId
记录当前的timeoutId。 -
clearTimeout(timeoutId)
每次调用函数时,清除之前的定时器,避免不必要的执行。 -
setTimeout(() => func(...args), delay)
创建新的定时器,在delay
毫秒后执行传入的函数func
。 -
func(...args)
执行函数,并传递参数。
关键:
- Debounce 返回了
timeoutId
的引用形成闭包,让每次调用时都能访问和修改timeoutId
,确保每次debounced
函数被调用时都能清除上一次的定时器,并启动新的定时器。
功能:
- 在一段时间内延迟执行函数,如果在这段时间内再次调用,
clearTimeout(timeoutId)
会清除掉定时器 ID,则重新计时。
用途:
-
常用于防止短时间内的重复触发,比如搜索框输入事件。
-
判断滚动结束后执行操作,比如上报数据或者执行动画。