window.scrollTo with setTimeout 进入无限循环,但没有 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);
}

现在它以无限循环结束,我假设由于异步跳出而以某种方式。

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

一种选择是将其放入async函数中,并awaitwhile内 300ms 后解析的 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毫秒。

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

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()的部分,但是为了防止多个并发循环。

如果启动第二个循环并且前一个循环尚未完成,请终止前一个循环。

最新更新