防抖与节流的区别
- 防抖是在事件触发后,延迟一定时间执行函数,如果在延迟时间内再次触发事件,则重新计时;
- 节流是在规定的时间间隔内,只能触发一次函数。
防抖与节流的实现:
- 防抖函数示例如下:
javascript
function debounce(func, delay) {
let timer;
return function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(func, delay);
};
}
- 节流函数示例如下:
function throttle(func, interval) {
let lastTime = 0;
return function() {
const now = new Date().getTime();
if (now - lastTime >= interval) {
func.apply(this, arguments);
lastTime = now;
}
};
}

1351

被折叠的 条评论
为什么被折叠?



