How to trigger ajax request on scroll stop?

后端 未结 3 1569
星月不相逢
星月不相逢 2021-01-07 04:26

On window scroll I\'m doing ajax request like this

$(window).scroll(function(){
 //doing ajax request
});

but it is creating multiple ajax

相关标签:
3条回答
  • 2021-01-07 05:03

    I don't believe there's an onscrollstop listener, but you can emulate it by setting a timeout and clearing it if scrolling continues.

    var timeout = null;
    
    $(window).scroll(function() {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            // do your ajax request
        }, 100);
    });
    
    0 讨论(0)
  • 2021-01-07 05:05

    You should wait a short period, and only trigger the request if no more scroll events happen.

    var timer, // store a timeout reference
        pendingAjax, // store the last AJAX request
        scrollHandler = function() {
            pendingAjax.abort(); // cancel the last request if it's still running
            pendingAjax = $.ajax({...}); // start a new AJAX request
        };
    
    $(window).scroll(function() { // whenever the window is scrolled
        clearTimeout(timer); // cancel the existing timer
        timer = setTimeout(scrollHandler, 300); // and start a new one
    });
    
    0 讨论(0)
  • 2021-01-07 05:08

    This question offers one solution.

    Another way to do this, rather than a timer, is to simply set a flag that indicates that an ajax request is already running, and to do nothing until the flag is cleared by the original request. You could also set a timer after the flag is cleared, if you wanted the ajax requests to not happen any more often than some arbitrary frequency (e.g. no more often than every 5 seconds).

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