1.节流
节流是一种用于控制函数执行频率的优化技术。它通过限制函数的调用速率,以便在高频率事件中减少函数的执行次数。节流可以使函数在一定的时间间隔内最多只执行一次,从而减轻计算量和提高性能。
function throttle(func, delay) {
let timerId;
return function() {
if (!timerId) {
timerId = setTimeout(() => {
func.apply(this, arguments);
timerId = null;
}, delay);
}
};
}
function handleScroll() {
console.log("滚动事件被触发了!");
}
const throttledScroll = throttle(handleScroll, 200);
window.addEventListener('scroll', throttledScroll);
2.防抖
防抖是一种用于控制函数执行频率的优化技术。它通过延迟函数的执行时间,直到一段连续的触发事件停止后的指定时间间隔,从而减少函数的执行次数。防抖可以用于减少频繁触发的事件中函数的执行次数,从而提高性能和响应速度。
function debounce(func, delay) {
let timerId;
return function() {
clearTimeout(timerId);
timerId = setTimeout(() => {
func.apply(this, arguments);
}, delay);
};
}
function handleInput() {
console.log("输入事件被触发了!");
}
const debouncedInput = debounce(handleInput, 200);
input.addEventListener('input', debouncedInput);