JS 防抖和节流
JS中的防抖(debounce)和节流(throttle)都是用来控制函数执行频率的技术。
防抖是指在函数被连续调用时,只有在指定的时间间隔内没有再次调用时,才会执行该函数。简单来说,就是在一段时间内只执行最后一次调用。
节流是指在函数被连续调用时,只有在指定的时间间隔内执行一次函数。简单来说,就是在一段时间内只执行一次调用。
下面是一个实现防抖的例子:
function debounce(func, delay) {
let timerId;
return function() {
clearTimeout(timerId);
timerId = setTimeout(func, delay);
}
}
function handleInput() {
console.log('Input event fired');
}
const debouncedHandleInput = debounce(handleInput, 300);
// 添加事件监听
document.querySelector('input').addEventListener('input', debouncedHandleInput);
在上面的例子中,debounce函数接收一个函数和延迟时间作为参数,返回一个新的函数。新函数内部使用setTimeout来延迟执行传入的函数,如果在延迟时间内再次调用,会清除之前的延迟并重新设置一个新的延迟。
下面是一个实现节流的例子:
function throttle(func, delay) {
let timerId;
let lastExecTime = 0;
return function() {
const now = Date.now();
if (now - lastExecTime >= delay) {
func();
lastExecTime = now;
} else {
clearTimeout(timerId);
timerId = setTimeout(func, delay);
}
}
}
function handleScroll() {
console.log('Scroll event fired');
}
const throttledHandleScroll = throttle(handleScroll, 300);
// 添加事件监听
window.addEventListener('scroll', throttledHandleScroll);
在上面的例子中,throttle函数接收一个函数和时间间隔作为参数,返回一个新的函数。新函数内部通过比较当前时间和上次执行时间的差值,来决定是否执行传入的函数。如果时间间隔大于指定的延迟时间,则立即执行函数;否则,设置一个延迟来延迟执行函数
原文地址: http://www.cveoy.top/t/topic/iyUj 著作权归作者所有。请勿转载和采集!