防抖和节流是什么
防抖与节流本质上是优化高频率执行代码的一种手段
如:浏览器的 resize、scroll、mousemove 等事件在触发时,会不断地调用绑定在事件上的回调函数,极大地浪费资源,降低前端性能
为了优化体验,需要对这类事件进行调用次数的限制,对此我们就可以采用防抖和节流的方式来减少调用频率
防抖(Debounce)
防抖的概念是在指定时间段内,多次触发同一事件后只执行一次处理函数。例如,当用户连续快速点击按钮时,只有最后一次点击会触发事件处理函数。这可以避免频繁触发处理函数导致的性能问题。
function debounce(func, delay) {
let timer;
return function() {
clearTimeout(timeoutId);
timer = setTimeout(() => {
func.apply(this, arguments);
}, delay);
};
}
//延迟500毫秒执行处理函数
const debouncedFunc = debounce(function() {
console.log('Executing debounce...');
}, 500);
// 多次调用,在500毫秒内只执行最后一次调用
debouncedFunc();
debouncedFunc();
debouncedFunc();
节流(Throttle)
节流的概念是在指定时间段内,限制事件处理函数的执行频率,提高代码性能。例如,当用户持续触发某个事件时,每隔一定时间执行一次事件处理函数。这可以减少过多的计算和渲染操作。
function throttle(func, delay) {
let timerId;
let lastExecTime = 0;
return function () {
const now = Date.now();
const elapsedTime = now - lastExecTime;
if (elapsedTime >= delay) {
// 执行处理函数
func.apply(this, arguments);
lastExecTime = now;
} else {
// 延迟至下一个时间段执行处理函数
clearTimeout(timerId);
timerId = setTimeout(() => {
func.apply(this, arguments);
lastExecTime = Date.now();
}, delay - elapsedTime);
}
};
}
// 限制每隔500毫秒执行一次处理函数
const throttledFunc = throttle(function () {
console.log('Executing throttle...');
}, 500);
// 多次调用,在500毫秒内只执行一次调用
throttledFunc();
throttledFunc();
throttledFunc();
区别
-
共同点: 都使用了闭包减少全局变量, 都可以使用setTimeout函数实现, 都是为了降低回调函数执行频率节省计算资源
-
不同点: 防抖在事件发生后执行回调,节流在事件持续发生过程中按照一定时间间隔执行回调。