window.scrollTo 使用 setTimeout 进入无限循环但没有 setTimeout 工作正常

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

我正在编写一个脚本,它会向下滚动页面以完全加载它以进行进一步处理,具有以下非常基本的功能,滚动跳转到底部但它无法加载中间的所有内容

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

所以我用 setTimeout 修改了它,这样它会滚动得更慢,并为页面加载它的内容留出时间。

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

现在它以无限循环结束,我假设是由于异步从 while 中跳出。

如何修改上面的脚本使其缓慢向下滚动以便加载所有内容?或者只是强制页面以其他方式加载所有内容

一个选项是将其放入 async 函数中,await 一个在 while:

中 300 毫秒后解析的 Promise
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);
  }
})();

setTimeout(func, n) 队列 func 被调入(至少)n ms.

所以你的第二种方法基本上是

while (document.documentElement.scrollTop <= document.body.scrollHeight - 500) {
  addAnotherTimeout();
}

循环内的代码对循环的条件没有影响,这就是为什么你在这里得到一个无限循环。

这里是一个递归版本(有点):

var scrollTimeout;
function scrollElement(){
    clearTimeout(scrollTimeout);
    if(document.documentElement.scrollTop <= document.body.scrollHeight-500){
        window.scrollTo(0, document.documentElement.scrollTop+500);
        scrollTimeout = setTimeout(scrollElement, 300);
    }
}

// start the scrolling:
scrollElement();

scrollElement()开头的clearTimeout()部分不是loop/recursion本身需要的,但是为了防止多个并发循环。

如果你开始第二个循环,而前一个循环还没有完成,就杀死前一个循环。