【问题标题】:setTimeout isn't working properly in the while loop [duplicate]setTimeout 在 while 循环中无法正常工作 [重复]
【发布时间】:2021-10-30 07:19:04
【问题描述】:

我需要它在每个循环结束时暂停 3 秒,但它没有暂停。我该如何解决?示例代码将不胜感激。

function file_get_contents(url, callback) {
  fetch(url).then(res => res.text()).then(text => callback(text));
}

function theCallBack(text) {
  text = text.replace(/google/g, "")
  let matches = text.match(/www.[a-z\-]+?.com/g);
  console.log(matches[0]);
};

var theArray = ["https://www.google.com/search?q=one", "https://www.google.com/search?q=two", "https://www.google.com/search?q=three"];
var count = theArray.length;

while (count > 0) {
  console.log(count);
  count--;
  file_get_contents(theArray[count], theCallBack);
  setTimeout(function() {}, 3000);
}

【问题讨论】:

  • 你需要暂停什么?
  • while 循环不等待setTimeouts
  • 3 seconds at the end of every loop,你的意思是3 seconds at the end of every successful fetch() 吗?

标签: javascript


【解决方案1】:

您可以使用Promise 暂停程序并使用await 它。

const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));


function file_get_contents(url, callback) {
  fetch(url).then(res => res.text()).then(text => callback(text));
}

function theCallBack(text) {
  text = text.replace(/google/g, "")
  let matches = text.match(/www.[a-z\-]+?.com/g);
  console.log(matches[0]);
};

var theArray = ["https://www.google.com/search?q=one", "https://www.google.com/search?q=two", "https://www.google.com/search?q=three"];
var count = theArray.length;



(async() => {
  for (let i = 0; i < count; i++) {
    console.log(i + 1);
    file_get_contents(theArray[i], theCallBack);
    await wait(3000);
  }
})();

【讨论】:

  • 出现资源加载失败错误。如果你运行代码 sn-p 它也只会显示 1、2、3。
  • 发现错误,需要将theArray[count]替换为theArray[i]
  • lol thx 指出。现已修复!
【解决方案2】:

我认为问题在于 setTineout() 异步函数,因此您需要使其同步,才能按您的意愿工作。

https://developer.mozilla.org/ru/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals

https://stackoverflow.com/a/50357618

【讨论】:

    猜你喜欢
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多