简体   繁体   中英

Fire event on wheel scroll only once js

IMPORTANT: I do know how to detect whether the scroll is up or down (and there are some similar answered questions on this website as well), but I don't know how to do the following: I want to perform some func on whether the wheel scroll is up or down; I have the following code:

window.addEventListener('wheel',wheel);
    function wheel(e){
        delta = e.deltaY;
        if (delta > 0) {
            Func1();
        } else  {
            Func2();
        }
    }

But with this code the functions are being called all the time while the wheel event continues, while I just simply need to call them once every time a new wheel event happens. how can I go around that?

You will need to add delay in executing your function of around 300 ms. After timeout if still event is occurring then set new timeout by clearing older one.

Check below snippet.

var wheel_timer = 0

window.addEventListener('wheel', function (e) {
    clearTimeout(wheel_timer);
    wheel_timer = setTimeout(function () {
        wheel(e)
    }, 10)
});

function wheel(e) {
    delta = e.deltaY;
    if (delta > 0) {
        Func1();
    } else {
        Func2();
    }
}

One suggestion can be instead of using wheel event you can you scroll event.

Edit : Improved answer to give a immediate response.

(updated to support multiple scrolls in the same direction and called each function immediately when we start scrolling)

You could save the state:

var scrollingDirection = 0; //idle
var lastScroll = 9999;
var scrollIdleTime = 300; // time interval that we consider a new scroll event
window.addEventListener('wheel',wheel);
function wheel(e){
    var delta = e.deltaY;
    var timeNow = performance.now();
    if (delta > 0 && ( scrollingDirection != 1 || timeNow > lastScroll + scrollIdleTime) ) {
        Func1();
        scrollingDirection = 1;
    } else if (delta < 0 && ( scrollingDirection != 2 || timeNow > lastScroll + scrollIdleTime)) {
        Func2();
        scrollingDirection = 2;
    }
    lastScroll = timeNow;
}

 var scrolled = true; window.addEventListener('wheel',wheel); function wheel(e){ if(scrolled == true){ scrolled = false delta = e.deltaY; if (delta > 0) { Func1(); } else { Func2(); } } } function Func1(){ console.log('1'+ scrolled); } function Func2(){ console.log('2' + scrolled) }

you can do this by adding an if-else block inside your scroll function,

as per my snippet above, the variable scrolled is by default set as true and when you make a scroll scrolled variable become false so for the second time it won't again enter in if block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM