How to trigger ajax request on scroll stop?

2020-03-06 08:16发布

问题:

On window scroll I'm doing ajax request like this

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

but it is creating multiple ajax request for scroll event. Is there any event like onscrollstop or something which only trigger after window scroll end. Or is there any other way I can handle the same scenario. Please suggest.

回答1:

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);
});


回答2:

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
});


回答3:

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).