Prevent AJAX Request Stacking

I have a problem that I cannot solve.

I am currently implementing an AJAX function similar to the one used by Twitter - to get new posts when scrolling.

jQuery looks something like this:

$(window).scroll(function(){ if($(window).scrollTop() == $(document).height() - $(window).height()){ $('div#ajaxloader').show(); $.ajax({ url: "loader.php?lastid=" + $(".container:last").attr("id"), success: function(html){ if(html){ $("#main").append(html); $('div#ajaxloader').hide(); }else{ $('div#ajaxloader').html('No more posts to show.'); } } }); } }); 

Now the problem; if the user scrolls fast and the database does it fast: jQuery doesn't seem to be able to send the correct id as a query fast enough, resulting in double messages.

Does anyone have a good idea on how to prevent this?

+4
source share
2 answers

Try the following:

  var runningRequest = 0; $(window).scroll(function(){ if(runningRequest <1){ if($(window).scrollTop() == $(document).height() - $(window).height()){ runningRequest++; $('div#ajaxloader').show(); $.ajax({ url: "loader.php?lastid=" + $(".container:last").attr("id"), success: function(html){ runningRequest--; if(html){ $("#main").append(html); $('div#ajaxloader').hide(); }else{ $('div#ajaxloader').html('No more posts to show.'); } } error: function(){runningRequest--;} }); } } }); 
+5
source

I would set the boolean to true before making my request, and whenever the request completes, I would return it to false. Then I would wrap the code that makes the request in checking if this value is true or false. I would also add a bool that tells me whether I should even worry about making a request - it makes no sense to ask if the last request is returned empty (if perhaps the data set has not changed since the last request). Anyway, here is the code that I would start with:

 ( function( global ) { var $ = global.jQuery, $win = $( global ), $doc = $( global.document ), $ajaxLoader = $( 'div#ajaxloader' ), $main = $( '#main' ), requestInProgress = false, outOfPosts = false; $win.scroll( function() { if( ! requestInProgress && ! outOfPosts && $win.scrollTop() === $doc.height() - $win.height() ) { requestInProgress = true; $ajaxLoader.show(); $.ajax( { url: 'loader.php', data: { lastid: $( '.container:last' ).attr( 'id' ) }, success: function( html ) { if( html ) { $main.append( html ); $ajaxLoader.hide(); } else { outOfPosts = true; $ajaxLoader.html( 'No more posts to show.' ); } }, complete: function() { requestInProgress = false; } } ); } } ); }( window ) ); 
+1
source

Source: https://habr.com/ru/post/1346216/


All Articles