如何在项目中实现一个节流函数?
实现节流函数可以通过时间戳或定时器方式控制函数执行频率。以下是两种常用实现方式:
基础时间戳版:
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));
特性说明:
适用场景:
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
2 回答4.7k 阅读✓ 已解决
4 回答4.3k 阅读✓ 已解决
可以引用
lodash
库:https://www.lodashjs.com/docs/lodash.throttle