首页 > 解决方案 > 加载单页应用程序的 Javascript 'while' 循环不起作用

问题描述

我正在尝试加载单页应用程序,直到我有一定数量的项目。我的函数传递了正确的新滚动高度,但代码不起作用。这是我的代码,我通过调用scrollInitiate()函数来启动它。我错过了什么?


function wait(ms){
    var start = new Date().getTime();
    var end = start;
    while(end < start + ms) {
      end = new Date().getTime();
   }
 }


function scrollInitiate() {
    while ($x('//*[@id="items"]/container').length < 200) {
        console.log("attempting");
        wait(5000);
        scrollIt(document.scrollingElement.scrollHeight);
    }
}

function scrollIt(height) {
    console.log("scrolling to: " + height);
    document.scrollingElement.scrollTo(0, height);
}

标签: javascripthtml

解决方案


while由于 javascript 的阻塞性质,您不能使用在 javascript 中等待。而是使用setTimeout

function scrollInitiate() {
  if ($x('//*[@id="items"]/container').length < 200) {
    console.log("attempting");
    scrollIt(document.scrollingElement.scrollHeight);
    setTimeout(scrollInitiate, 5000);
  }
  console.log("success");
}

推荐阅读