Debouncing Infinite Scroll

Hello,

Can someone teach me how to debounce the code for infinite scroll? I saw the solution given on this post (Why infinite will execute more than once?) but it uses Vue. Is there a way to do it properly for the standard Framework7 code? Here’s the code I’m using:

$$('.infinite-scroll-content').on('infinite', function () {
    alert("infinite was called.");
  });

Thanks in advance! :slight_smile:

Hi,
Here is the code, taken from the docs; just change it to your needs

// Attach 'infinite' event handler
$$('.infinite-scroll-content').on('infinite', function () {
  // Exit, if loading in progress
  if (!allowInfinite) return;

  // Set loading flag
  allowInfinite = false;

  // Emulate 1s loading
  setTimeout(function () {
    // Reset loading flag
    allowInfinite = true;

    if (lastItemIndex >= maxItems) {
      // Nothing more to load, detach infinite scroll events to prevent unnecessary loadings
      app.infiniteScroll.destroy('.infinite-scroll-content');
      // Remove preloader
      $$('.infinite-scroll-preloader').remove();
      return;
    }

    // Generate new items HTML
    var html = '';
    for (var i = lastItemIndex + 1; i <= lastItemIndex + itemsPerLoad; i++) {
      html += '<li>Item ' + i + '</li>';
    }

    // Append new items
    $$('.list ul').append(html);

    // Update last loaded index
    lastItemIndex = $$('.list li').length;
  }, 1000);
});

https://framework7.io/docs/infinite-scroll.html#example

Hello,

Thanks for your reply. Yes I’m aware of the code in the documentation and it’s what I currently have actually, I only replaced it with an alert so it’s simpler. However upon scrolling it triggers multiple times so to fix that I need to be able to add a debounce function to it so it will only execute once. Is there a way to add it? I tried using those I found on the Internet but I wasn’t able to make it work. Here’s an example: https://davidwalsh.name/javascript-debounce-function

jQuery also has a function for that, as well. I can’t get that to work either. :confused:

ok, so its an event, every time the event is emitted, it will run the code in the handler.
so you can use the docs approach

let allowInfinite = true
function handler () {
  // Exit, if loading in progress
  if (!allowInfinite) return;
  // Set loading flag
  allowInfinite = false;
  setTimeout(function () {
    // YOUR CODE HERE
    allowInfinite = true;
  }, 1000)
}

maybe the code i share dosn’t solve your problem.
Can you describe what are you trying to achieve?