Search code examples
javascriptajaxscroll

$(window).scroll(function() loads many times


I'm working with scroll function, the problem is that it loads many times and it doesn't wait for the new information plased by the db.

Here's the code!

$(document).ready(function(){
$(window).scroll(function(){
    var lastID = $('.load-more').attr('lastID');
    
     if(($('#postList').height() <= $(window).scrollTop() + $(window).height())&& (lastID != 0)){
        $.ajax({
            type:'POST',
            url:'getData.php',
            data:'id='+lastID,
            beforeSend:function(){
                $('.load-more').show();             },
            success:function(html){
                $('.load-more').remove();
                $('#postList').append(html);
            }
        });
    }
});

});

I hope you can help me, thanks!


Solution

  • If you simply want to prevent an AJAX request to start while another one is running, use a variable to return from the scroll function. Set it to true right before the AJAX request and reset it to false in the always handler:

    var loading = false;
    $(document).ready(function(){
        $(window).scroll(function(){
            if(loading)
                return;
    
            var lastID = $('.load-more').attr('lastID');
            
            if(($('#postList').height() <= $(window).scrollTop() + $(window).height())&& (lastID != 0)){
                loading = true;
                $.ajax({
                    type:'POST',
                    url:'getData.php',
                    data:'id='+lastID,
                    beforeSend:function(){
                        $('.load-more').show();             
                    },
                    success:function(html){
                        $('.load-more').remove();
                        $('#postList').append(html);
                    },
                    always: function() {
                        loading = false;
                    }
                });
            }
        });
    });
    

    (untested)

    As @ProfessorAbronsius suggested in the comments: Take a look at the Intersection Observer API as well. Seems to be a more stable approach.