在监听scroll事件的时候经常会用到防抖,当滚动到某一位置而触发状态,从而不会出现频繁滚动持续触发事件的情况
防抖的事件处理机制仅触发一次且必须是结束状态下才会执行
function debounce(fun, delay) {
let timer;
return function() {
timer && clearTimeout(timer);
timer = setTimeout(function() {
fun();
}, delay);
}
}
window.addEventListener('scroll',
debounce(function() {
console.log(document.documentElement.scrollTop);
}, 300)
);
防抖有个明显的缺点就是它在事件运行的过程中不能够执行事件,比如图片的懒加载就不能够满足,当滚动了很多但是由于没有停止导致图片仍然不会加载出来
节流的事件处理机制是在一定时间内无法重复调事件
function throttle(fun, delay) {
let timer, start;
return function starting() {
const now = Date.now();
if(!start) start = now;
timer && clearTimeout(timer);
if(now - start >= delay) {
fun();
start = now;
} else {
timer = setTimeout(function() {
starting();
}, 1);
}
}
}
window.addEventListener('scroll',
throttle(function() {
console.log(document.documentElement.scrollTop);
}, 1000)
);
原文:https://www.cnblogs.com/ljwk/p/10483365.html