防抖(debounce)
防抖的核心思想是:在事件被触发后,等待一段时间再执行函数。如果在这段时间内事件又被触发,则重新计时,直到等待时间过后才执行一次函数。
节流(throttle)
节流的核心思想是:在一定时间内,只执行一次函数。即使事件被多次触发,也会按照固定的时间间隔执行。
下面我们分别实现防抖和节流函数,并给出一个在线运行的示例。
防抖函数实现
function debounce(func, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
节流函数实现(使用时间戳)
function throttle(func, delay) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= delay) {
func.apply(this, args);
lastTime = now;
}
};
}