Scroll event firing too many times. I only want it to fire a maximum of, say, once per second

后端 未结 8 725
再見小時候
再見小時候 2020-11-27 12:24

I have a page with \"infinite scroll\". It calculates the difference between the end of the page and the current page and loads more content if this difference is small enou

8条回答
  •  醉梦人生
    2020-11-27 12:42

    One way to solve this problem is to define a time interval and only process a scroll event once within that time interval. If more than one scroll event comes in during that time interval, you ignore it and process it only when that time interval has passed.

    var scrollTimer, lastScrollFireTime = 0;
    
    $(window).on('scroll', function() {
    
        var minScrollTime = 100;
        var now = new Date().getTime();
    
        function processScroll() {
            console.log(new Date().getTime().toString());
        }
    
        if (!scrollTimer) {
            if (now - lastScrollFireTime > (3 * minScrollTime)) {
                processScroll();   // fire immediately on first scroll
                lastScrollFireTime = now;
            }
            scrollTimer = setTimeout(function() {
                scrollTimer = null;
                lastScrollFireTime = new Date().getTime();
                processScroll();
            }, minScrollTime);
        }
    });
    

    This will fire the first scroll event immediately and then get you a scroll event approximately once every 100ms while the scrollbar is being moved and then one final event after the scrollbar stops moving. You can adjust the frequency of the event by changing the argument to the setTimeout (what is currently set to 100).

    There is a demo here: http://jsfiddle.net/jfriend00/EBEqZ/ which you need to open a debug console window, start moving the scrollbar in the content window and then watch the time of each scroll event in the debug console window. On my version of Chrome, they are set for a minimum spacing of 100ms and they seem to occur every 100-200ms.

提交回复
热议问题