简体   繁体   English

在执行下一行代码之前等待几秒钟?

[英]Wait for a few seconds before executing next line of code?

The purpose of this code is to retrieve the URLs of search results.此代码的目的是检索搜索结果的 URL。 The website I am working with doesn't load all of the results unless you scroll the entire page.除非您滚动整个页面,否则我正在使用的网站不会加载所有结果。 However, it takes a few seconds after scrolling for all of the results to load, and as it is, the next line is executed right away and it only retrieves the first few links instead of the entire page.但是,滚动后需要几秒钟才能加载所有结果,事实上,下一行会立即执行,它只检索前几个链接而不是整个页面。

I think all I need for this to work is just a pause for a few seconds.我想我所需要的只是暂停几秒钟。

The xpath in this example is for google which doesn't lazy load, the site I'm using is behind a login and it does lazy load.此示例中的 xpath 用于不延迟加载的 google,我使用的站点位于登录名后面,并且它执行延迟加载。

window.scrollTo({ top:document.body.scrollHeight, behavior: 'smooth', })

///pause here

try {

  var maxLinks = 25;  
  var returnData = "URL";  
  var xPath = '//*[@class="r"]/a';

  var xpathResults = document.evaluate(xPath, document, null, 0, null);

  var oNode = xpathResults.iterateNext();

  var nodeList = [];
  var linkCount = 0;
  var hrefStr;
  var returnStr;
  var linkText;

  while (oNode && (linkCount < maxLinks)) {

    if (oNode.href !== hrefStr) {
      linkCount += 1;
      hrefStr = oNode.href;
      linkText = oNode.textContent;

      if (returnData === "MD") {
        returnStr = "[" + linkText + "](" + hrefStr + ")";
      }
      else {
        returnStr = hrefStr;
      }

      nodeList.push(returnStr);
    }

    oNode = xpathResults.iterateNext();

  } 

  returnResults = nodeList.join('\n');


} catch (pError) {

    if (!oError.message) {
      oError.message = pError.toString();
    }

    oError.message = "[ERROR]"
      + "\n\nError Number: " + oError.errorNumber + "\n"
      + oError.message

    returnResults = oError.message;  
} 

function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard(returnResults)
copyToClipboard(returnResults)

There is sleep method solution that allows you to wait time between actions as I mentioned in my comment earlier.正如我之前在评论中提到的,有一种睡眠方法解决方案可以让您在操作之间等待时间。

Here is my solution:这是我的解决方案:

    function sleep (time) { //Sleep function
      return new Promise((resolve) => setTimeout(resolve, time));
    }
    sleep(500).then(() => { //Wait the stated time then do something..
         var maxLinks = 25;  
  var returnData = "URL";  
  var xPath = '//*[@class="r"]/a';

  var xpathResults = document.evaluate(xPath, document, null, 0, null);

  var oNode = xpathResults.iterateNext();

  var nodeList = [];
  var linkCount = 0;
  var hrefStr;
  var returnStr;
  var linkText;

  while (oNode && (linkCount < maxLinks)) {

if (oNode.href !== hrefStr) {
  linkCount += 1;
  hrefStr = oNode.href;
  linkText = oNode.textContent;

  if (returnData === "MD") {
    returnStr = "[" + linkText + "](" + hrefStr + ")";
  }
  else {
    returnStr = hrefStr;
  }

  nodeList.push(returnStr);
}

oNode = xpathResults.iterateNext();

  } 

  returnResults = nodeList.join('\n');


} catch (pError) {

    if (!oError.message) {
      oError.message = pError.toString();
    }

    oError.message = "[ERROR]"
      + "\n\nError Number: " + oError.errorNumber + "\n"
      + oError.message

    returnResults = oError.message;  
} 

function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard(returnResults)
copyToClipboard(returnResults)
});
   }

There isn't a sleep() in the same way that there is in Java.没有像 Java 中那样的 sleep() 。 If you don't understand why, you'll need to read about threading (or the lack thereof) in JavaScript.如果您不明白为什么,您需要阅读 JavaScript 中的线程(或缺少线程)。 However, you can create an async function and then call it with an await (but your code will need to be in an async function:但是,您可以创建一个异步函数,然后使用 await 调用它(但您的代码需要在异步函数中:

function sleep(millis) {
  return new Promise(resolve => setTimeout(resolve, millis));
}


async function doIt() {
    const max = 4;
    let count = 0;
    while (count < max) {
        await sleep(1000);
        console.log('loop: %s', count);
        count++;
    }
}

doIt();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM