window.addEventListener('scroll',handleScroll);
function handleScroll(){
let scrollPosition = window.pageYOffset || window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;
if(scrollPosition >50)
console.log('Viewport scrolled more than 50px')
else
console.log('Viewport scrolled less than 50px')
}
let optimizedHandlerScroll = debounce(handleScroll, 200);
window.addEventListener('scroll',optimizedHandlerScroll);
function handleScroll(){
let scrollPosition = window.pageYOffset || window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;
if(scrollPosition >=50){
console.log('more than 50')
}
else
console.log('less than 50')
}
function debounce(fn, delay) {
let timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(function () {
fn();
}, delay);
};
}
The initial basic version is functional, but it can be resource-intensive. The scroll event handler gets triggered multiple times. On the other hand, the improved version in the gist only executes the handler once you finish scrolling, making it more efficient.