开发者

How to trigger ajax request on scroll stop?

开发者 https://www.devze.com 2023-03-13 08:34 出处:网络
On window scroll I\'m doing ajax request like this $(window).scroll(function(){ //doing ajax request });

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 an开发者_运维技巧y 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.


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消