防抖(Debounce)和节流(Throttle)是常用的前端性能优化技术,可以限制函数的执行频率,提升用户体验。这里我为你介绍如何手动实现防抖和节流的功能。
1. 防抖:
防抖的原理是在事件被频繁触发时,只有等到一定的空闲时间过去后,才执行最后一次触发的函数。这样可以避免函数的过多执行。
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
}
}
// 示例使用
function handleInput() {
console.log('input event handled');
}
const debouncedHandleInput = debounce(handleInput, 500);
// 将 debouncedHandleInput 绑定到某个元素的事件上,比如输入框的 input 事件
inputElement.addEventListener('input', debouncedHandleInput);
在上述示例中,debounce
函数接收一个函数 func
和一个延迟时间 delay
,返回一个新的函数。在返回的函数中,使用 setTimeout
设置一个定时器,通过调用 clearTimeout
来清除上一次的定时器。这样,在每次调用返回的函数时,如果在 delay
时间内再次调用,都会清除之前的定时器,并重新设置一个新的定时器,在延迟时间结束后执行最后一次触发的函数。
2. 节流:
节流的原理是在一定时间间隔内,只执行一次函数。这样可以控制函数的执行频率,避免过多的计算或请求。
function throttle(func, delay) {
let waiting = false;
return function(...args) {
if (!waiting) {
func.apply(this, args);
waiting = true;
setTimeout(() => {
waiting = false;
}, delay);
}
}
}
// 示例使用
function handleScroll() {
console.log('scroll event handled');
}
const throttledHandleScroll = throttle(handleScroll, 200);
// 将 throttledHandleScroll 绑定到某个元素的事件上,比如窗口的 scroll 事件
window.addEventListener('scroll', throttledHandleScroll);