1

I have a chrome extension that scrolls to the bottom of a users page in order to load all their items (the site uses lazy load)

function makeProgressCountingAllItems() {
      // start off by counting all the items you see on the page
      allItems = document.getElementsByClassName('items');
            
      // scroll the last item currently loaded
      allItems[allItems.length - 1].scrollIntoView();
      document.dispatchEvent(new MouseEvent('scroll'));
    }

I then want to get all the items on the page (including the newly loaded ones) and put them in an array

function selectItems() {
    return document.getElementsByClassName('items')
}

But if I call both of these functions like this

makeProgressCountingAllItems();
selectItems();

The problem is my selectItems function runs before the makeProgressCountingAllItems function gets a chance to scroll to the bottom of the page.

How do I run the second function after the first function is complete?

JoeM
  • 23
  • 5

1 Answers1

-1

I think that your Question's title it's not appropiate for the feature you're asking, because ideally you want to listen for new items to be added you don't need to worry about waiting the scroll function to finish.

For listening changes in the DOM you can use a MutationObserver. See this question as reference.

If you want to wait until the scroll function finishes it's not possible with the current API.

At this moment there's an open request to include a callback when scrollIntoView animation ends, you can see the thread of this request here and a workaround for your question here.

Adding a setTimeout is the best option you have, here's an example:

makeProgressCountingAllItems();
setTimeOut(()=> { selectItems(); },500);
F-nixro
  • 124
  • 4