如何在项目中实现一个节流函数?
实现节流函数可以通过时间戳或定时器方式控制函数执行频率。以下是两种常用实现方式:
基础时间戳版:
function throttle(func, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
func.apply(this, args);
lastTime = now;
}
};
}
增强版(首尾双触发):
function throttle(func, delay) {
let lastTime = 0;
let timeoutId = null;
return function(...args) {
const context = this;
const now = Date.now();
if (now - lastTime >= delay) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
func.apply(context, args);
lastTime = now;
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(context, args);
lastTime = Date.now();
timeoutId = null;
}, delay - (now - lastTime));
}
};
}
使用示例:
// 处理滚动事件
window.addEventListener('scroll', throttle(() => {
console.log('处理滚动逻辑');
}, 200));
// 处理输入框自动补全
inputElement.addEventListener('input', throttle(searchSuggestions, 300));
特性说明:
适用场景:
13 回答12.6k 阅读
7 回答1.7k 阅读
9 回答1.5k 阅读✓ 已解决
3 回答1k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
可以引用
lodash
库:https://www.lodashjs.com/docs/lodash.throttle