Scroll Function Firing Multiple Times Instead of Once

前端 未结 2 1501
一向
一向 2021-01-06 01:59

I am trying to create a website that automatically scrolls to each section upon a single scroll action. This means that the code has to check if the page is scrolled up or s

相关标签:
2条回答
  • 2021-01-06 02:58

    The scroll event (as well as the resize event) fire multiple times as a user does this. To help this, the best practice is to debounce. However, I've never gotten that to work. Instead, I use a global boolean to check if the function has fired.

    var scrolled = false;
    page.on('scroll', function(){
        if(!scrolled){
            scrolled = true;
            //do stuff that should take a while...
            scrolled = false;
        };
    });
    
    0 讨论(0)
  • 2021-01-06 03:00

    This worked for me!

    var ScrollDebounce = true;
    $('.class').on('scroll',
    function () {
    if (ScrollDebounce) {
    ScrollDebounce = false;
    
    //do stuff    
    
    setTimeout(function () { ScrollDebounce = true; }, 500);
    }
    })
    
    0 讨论(0)
提交回复
热议问题