javascript - How to prevent JQuery script from repeating in a custom infinite scroll script -
i'm using latest jquery. problem if user scrolls fast script fires twice in row. if user scrolls @ normal speeds or slowly, script works normally. have js @ bottom of page. added timeout when calling function, wait timeout , repeats script twice. repeating doesn't happen time. have setting call function @ -10px of scroll height. also, attempt i've made put loading gif doesn't seem work, delay on loading gif. there way prevent 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 did delay function call, still queued 1 every time .scroll
event happened. if want implement delay need use settimeout()
prevent more 1 request within 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 update lastpostfunc()
function won't if previous ajax request 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 admit infinite scroll can annoying, use "load more" button/link instead.)
Comments
Post a Comment