前端节流实现
节流(Throttling)是一种限制函数执行频率的技术,确保函数在指定的时间间隔内最多只执行一次,无论触发了多少次事件。这在处理像滚动、窗口调整大小、鼠标移动等频繁触发的事件时非常有用。
以下是实现节流的几种方法:
1. 使用lodash库的throttle函数
lodash
提供了throttle
函数来实现节流功能。
// 引入lodash的throttle函数
import _ from 'lodash';
// 创建一个节流函数
const throttledFunction = _.throttle(function() {
// 这里是你的接口请求逻辑
console.log('接口请求被触发');
}, 1000); // 1000毫秒的延迟时间
// 使用节流函数
window.addEventListener('resize', throttledFunction);
2. 手动实现throttle函数
如果你不想引入额外的库,可以自己实现一个throttle
函数:
function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
// 使用节流函数
const myThrottledFunction = throttle(function() {
console.log('接口请求被触发');
}, 1000);
window.addEventListener('resize', myThrottledFunction);
3. 使用时间戳实现节流
这种方法确保在每个时间间隔的开始时执行一次函数。
function throttleByTimestamp(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
// 使用节流函数
const myThrottledFunctionTimestamp = throttleByTimestamp(function() {
console.log('接口请求被触发');
}, 1000);
window.addEventListener('resize', myThrottledFunctionTimestamp);
4. 使用requestAnimationFrame实现节流
对于某些场景,如窗口调整大小或滚动事件,可以使用requestAnimationFrame
来实现节流:
function throttleRAF(func, limit) {
let frame;
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
} else {
frame = requestAnimationFrame(() => {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
});
}
}
};
}
// 使用节流函数
const myThrottledFunctionRAF = throttleRAF(function() {
console.log('接口请求被触发');
}, 1000);
window.addEventListener('resize', myThrottledFunctionRAF);