【问题标题】:window.scrollTo with setTimeout goes into infinite loop but works fine without setTimeout带有 setTimeout 的 window.scrollTo 进入无限循环,但没有 setTimeout 可以正常工作
【发布时间】:2019-05-14 07:07:28
【问题描述】:

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

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。

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

【问题讨论】:

  • while循环阻塞执行,定时函数永远不会执行。

标签: javascript asynchronous scroll settimeout infinite-loop


【解决方案1】:

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()部分不是循环/递归本身所必需的,而是为了防止多个并发循环。

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

【讨论】:

  • "n 将始终 >= 10ms" 嗯...不。有一个 4ms 的限制,但这仅在回调的嵌套级别超过 5 级深度时才有效。 Timer initialisation steps • 11。从历史上看,这个限制在某些浏览器中确实设置为 10 毫秒,但这已经只是在一些嵌套级别之后。然而,这并没有改变这样一个事实,事实上,这至少会在下一个事件循环中触发。
【解决方案2】:

一种选择是将其放入async 函数中,并将await 放入while 内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);
  }
})();

【讨论】:

    猜你喜欢
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    相关资源
    最近更新 更多