Search code examples
javascriptasynchronousscrollsettimeoutinfinite-loop

window.scrollTo with setTimeout goes into infinite loop but works fine without setTimeout


I am writing a script that would scroll down the page to load it completely for further processing, with following very basic function, scroll jumps to the bottom but it fails to load everything in between

while(document.documentElement.scrollTop <= document.body.scrollHeight-500){
     window.scrollTo(0, document.documentElement.scrollTop+500);
}

so I have modified it with setTimeout so it would scroll it more slowly and give time for the page to load its stuff.

while (document.documentElement.scrollTop <= document.body.scrollHeight - 500) {
setTimeout(
    function() {
        window.scrollTo(0, document.documentElement.scrollTop + 500);
    }, 300);
}

Now it ends in an infinite loop, I am assuming due to async jumping out of while somehow.

How do I modify the above script to scroll it down slowly so it would load everything? Or just force the page to load everything in some other way


Solution

  • One option is to put it into an async function, and await a Promise that resolves after 300ms inside the while:

    const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
    (async () => {
      while (document.documentElement.scrollTop <= document.body.scrollHeight - 500) {
        window.scrollTo(0, document.documentElement.scrollTop + 500);
        await delay(300);
      }
    })();