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 firstHandlerScroll = debounce(handleScroll, 200);
window.addEventListener('scroll',firstHandlerScroll);
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 first naif version is ok, but is resource consuming. The scroll event handler is called very much times. The second version in the snippet instead call the handler only when you release the mouse after scroll, thus is much kind about efficiency