Patriotec
Patriotec

Reputation: 1144

How to prevent JQuery script from repeating in a custom infinite scroll script

I'm using the latest JQuery. The problem is if the user scrolls too fast the script fires twice in a row. If the user scrolls at normal speeds or very slowly, the script works normally. I have the js at the bottom of the page. I added a timeout when calling the function, but all it does is wait for the timeout and then repeats the script twice. The repeating doesn't happen all the time. I have the setting to call the function at -10px of the scroll height. Also, any attempt I've made to put a loading gif doesn't seem to work, even with a delay on loading the gif. Is there a way to prevent this from happening?

<body>
    <div class="contentholderwrap"></div>

    <div id="dataresult"></div>

</body>

<script type="text/javascript">
    $(document).ready(function(){
        function lastPostFunc(){
            var endid = $(".contentholderwrap:last").attr("id");
            if (endid != "1000000000000") {
                $.post("main.php?lastid="+$(".contentholderwrap:last").attr("id"), function(data) {
                    if (data != ""){
                        $(".contentholderwrap:last").after(data);
                    }
                    $('#dataresult').empty();
                });
            }
        };

    $(window).scroll(function(){
        if ($(window).scrollTop() >= $(document).height() - $(window).height() -10 ){
            setTimeout(lastPostFunc, 500);
        }
    });
});
</script>

Upvotes: 1

Views: 1553

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

Your timeout didn't work because all it did was delay the function call, but it still queued one up every time the .scroll event happened. If you want to implement a delay you need to use setTimeout() to prevent more than one request within a set period of time:

var timerid = null;
$(window).scroll(function(){
   if (timerid === null &&
       $(window).scrollTop() >= $(document).height() - $(window).height() -10 ){
         lastPostFunc();
         timerid = setTimeout(function() { timerid = null; }, 500);
   }
});

Alternatively you could update your lastPostFunc() function so that it won't do anything if the previous Ajax request is still in progress:

 var ajaxInProgress = false;
 function lastPostFunc(){
     if (ajaxInProgress) return;

     var endid = $(".contentholderwrap:last").attr("id");
     if (endid != "1000000000000") {
         $.post("main.php?lastid="+endid, function(data) {
             if (data != ""){
                $(".contentholderwrap:last").after(data);
             }
             $('#dataresult').empty();
             ajaxInProgress = false;
         });
         ajaxInProgress = true;
     }
 }

(A third option is to admit that infinite scroll can be really annoying, so use a "Load more" button/link instead.)

Upvotes: 4

Related Questions