0

when someone would immediatly scroll to the bottom after loading the code it would sometimes not update the id on time and load the same query heres my script

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
window.onscroll = function() {
  if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
    var lastId = $(".postid:last").attr("id");
    var elem = document.getElementById("ele");
    setTimeout(() => {
        getMoreData(lastId);
        elem.scrollIntoView();
    }, 0);
  }
}

function getMoreData(lastId) {
       $(window).off("scroll");
    $.ajax({
        url: 'load_more.php?lastId=' + lastId,
        type: "get",
        beforeSend: function ()
        {
            $('.ajax-loader').show();
        },
        success: function (data) {
               setTimeout(function() {
                $('.ajax-loader').hide();
            $("#post-list").append(data);
               },1000);
        }
   });
}
</script>
Geert
  • 13
  • 2
  • Have you considered the [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) a sthe means by which to trigger fresh ajax calls? Also - in the js you reference `document.getElementById("ele");` is there more than one of these? – Professor Abronsius Oct 15 '22 at 16:48
  • No theres only one – Geert Oct 15 '22 at 16:49
  • You can always create an array of id's that have already been loaded and if the `lastId` is in it, just give a return in the `getMoreData` function. – Robert Oct 15 '22 at 17:07

1 Answers1

0

What you probably want is to throttle the ajax requests after scroll event (say no more than once per 250ms).

You may use this function:

function throttle(func, timeFrame) {
  var lastTime = 0;
  return function() {
    var now = Date.now();
    if (now - lastTime >= timeFrame) {
      func();
      lastTime = now;
    }
  };
}

var count = 1;

var throttled = throttle(function() {
  console.log("doing ajax " + count++);
}, 250)
window.addEventListener('scroll', throttled)
<body style="height: 4000px">
  keep scrolling no matter what
</body>
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • That still doesn't work for me but the double loading seems to happen when i scroll upwards after just loading something – Geert Oct 25 '22 at 14:49