节流是一种优化性能的技术,它可以限制一个函数在一定时间内被频繁调用的次数。
节流的主要思想是,当一个函数被调用后,它在指定的时间间隔内只能被执行一次,即使在这段时间内多次触发了该函数。这可以有效地减少函数的执行次数,特别是在处理一些频繁触发的事件(比如滚动、拖拽、输入等)时,节流可以提高页面的性能和响应速度。
function throttle(func, delay) {
let lastExecuted = 0;
return function() {
const now = Date.now();
if (now - lastExecuted >= delay) {
func.apply(this, arguments);
lastExecuted = now;
}
};
}
// 使用节流函数
const throttledFunction = throttle(function() {
console.log('Throttled function executed');
}, 200);
// 绑定事件
window.addEventListener('scroll', throttledFunction);