0

I am doing a Web Scraping Project with Youtube. I need to automatically scroll to the bottom via Javascript. I am inputting the command in Google Chrome Inspect Console Terminal.

This link: https://stackoverflow.com/a/29971996/3326078 showed me to use this:

window.scrollTo(0, document.body.scrollHeight ||document.documentElement.scrollHeight);

Above works as expected.

However when I do,

for (var i = 0; i < 5; i++) {  
    setTimeout(window.scrollTo(0, document.body.scrollHeight 
|| document.documentElement.scrollHeight),5)}

it doesn't repeat more than once. Can someone explain to me whether what I am trying to do is possible. Again, I am inputting this command in the Google Chrome Inspector Console.

Thanks!

user3326078
  • 617
  • 1
  • 9
  • 19

1 Answers1

2

A for loop isn't going to wait for setTimeout to complete before it continues running. If you want the scrolling to wait for setTimeout to finish and run a certain amount of times, you'll need a function that calls the timeout and the calling function again inside of it.

Many ways to do this, but here is my implementation:

var scrollToBottomWithTimeout = function (param_iterations, param_wait_time) {
  setTimeout(function () {
    window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);

    if (param_iterations > 0) {
      param_iterations = param_iterations - 1;
      scrollToBottomWithTimeout(param_iterations, param_wait_time);
    }
  }, param_wait_time);
};

Once declared, this function can be called like so:

scrollToBottomWithTimeout(5, 1000);

The param_wait_time in milliseconds (thousandths of a second).

林果皞
  • 7,539
  • 3
  • 55
  • 70
Ashton French
  • 370
  • 2
  • 12