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

后端 未结 8 635
再見小時候
再見小時候 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 13:08

    Here is a solution that doesn't require the use of an extra JS library or plugin, that aims for simplicity. It might not be as efficient as other implementations but it is definitely a step up from firing your main event every time you scroll.

    This was taken from this blog post by Danny Van Kooten. Which I have used in delaying my onscroll() events for my back-to-top button on my blog.

    var timer;
    $(window).scroll(function() {
        if(timer) {
            window.clearTimeout(timer);
        }
        timer = window.setTimeout(function() {
           // actual code here. Your call back function.
        console.log( "Firing!" );
        }, 100);
    });
    

    You can also further improve performance by moving out variables out of the callback function to avoid unnecessary recalculations, for example the value of $(window).height() or height of some static div element that won't change once the page is loaded.

    Here's an example that is adapted from my use case.

    var scrollHeight = $("#main-element").height(); //never changes, no need to recalculate.
    $(window).on('scroll', function() {
        if (timer) 
            window.clearTimeout(timer);
        timer = window.setTimeout(function() {
            var scrollPosition = $(window).height() + $(window).scrollTop();    
            if ($(window).scrollTop() < 500)
                $(".toggle").fadeIn(800);
            else 
                $(".toggle").fadeOut(800);
        }, 150); //only fire every 150 ms.
    });
    

    This limits the actual function to only execute every 150ms, or else reset the timer back to 0 if 150ms has not passed. Tweak the value to suit what you need.

    0 讨论(0)
  • 2020-11-27 13:08

    the scroll fire multiple times is correct and you should able to get the scroll position differently each time. I think you need to set a timer when you first get in the scroll event like you mentioned x milliseconds, and also record the time stamp, and then next time scroll event fire, check the last trigger time and ignore it if it's within x milliseconds, and do the real job in your Timer action.

    0 讨论(0)
提交回复
热议问题