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>
Your timeout didn’t work because all it did was delay the function call, but it still queued one up every time the
.scrollevent happened. If you want to implement a delay you need to usesetTimeout()to prevent more than one request within a set period of time:Alternatively you could update your
lastPostFunc()function so that it won’t do anything if the previous Ajax request is still in progress:(A third option is to admit that infinite scroll can be really annoying, so use a “Load more” button/link instead.)