1

I am working on an infinite scroll to display data with an Angular component. The idea is when I got scroll event, I will ask to have more data by change the value of limit when call the API.

I will stop call the API if the data.length < limit && data.length === currentData.length but because everything is async so that this component call at least 10 times the same request for increasing limit to receive the same data. The logic to stop the call is inside the subscribe handler.

I think I need to catch scroll end event not only scroll but this event not exists, is there any other approach to this problem?

Raphaël VO
  • 2,413
  • 4
  • 19
  • 32

2 Answers2

1

If i understand correctly, the problem you're experiencing is caused by the scroll event triggered multiple times by the browser. what you can do to avoid this big overhead is to implement a simple debounce mechanism to avoid calling the same api multiple times within a specific interval.

something like:

function debounce(fn, debounceTime = 500) {
  let timeout = -1;
  const currentScope = this;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(fn.bind(currentScope, ...args), debounceTime);
  }
}

and then call your loadData function

const softLoadData = debounce(loadData);

at this point your new function softLoadData won't be called more than once within an interval of 500ms (that you can choose) up to your needs.

Karim
  • 8,454
  • 3
  • 25
  • 33
0

I think you should mark some boolean as "waiting for data" - and as long as the data hasn't completely loaded and the updated accordingly refreshed, the scroll event will do nothing.

Shushan
  • 1,235
  • 1
  • 10
  • 15