javascript - 如何在循环内使用 JavaScript 创建 waitFor(delay) 函数?

标签 javascript node.js settimeout

我正在尝试在 Node.js 的循环内添加延迟。我有一个数组,需要为数组的每个元素调用一个函数。问题是每次这样的函数调用应该有 30 秒的间隔。这是我尝试过的 -

const cprRedshift = async (page) => {
    let query = "select links from schema.table", links = [], ranks = []
    let data = await redshiftSelect(query)
    data.rows.forEach(element => {
        links.push(element.links)
    })

    let hostnames = await getDomainNames(links)

    // one way
    for(let i = 0; i < hostnames.length; i++){
            await setTimeout(async () => await checkPageRank(hostnames[i]), 30000)
    }

    // another way    
    let i = 0
    while(i < hostnames.length){
        await checkPageRank(page, hostnames[i])
        setInterval(() => ++i, 30000)
    }
}

checkPageRank 是同一脚本中的一个函数,我需要为 hostnames[] 数组中的所有元素调用它,同时在每次调用之间保持 30 秒的间隔。任何关于如何实现这一目标的想法将不胜感激。谢谢!

最佳答案

下面是执行此类操作的常见模式的简化示例:

const hostnames = ["one", "two", "three", "four", "five", "six"];

function go (index = 0) {
  // do whatever you need to do for the current index.
  console.log(hostnames[index]);
  
  // if we haven't reached the end set a timeout
  // to call this function again with the next index.
  if (hostnames.length > index + 1) {
    setTimeout(() => go(index + 1), 1000);
  }
}

// kick it off
go();

关于javascript - 如何在循环内使用 JavaScript 创建 waitFor(delay) 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56285655/

相关文章:

javascript - 在 Javascripts 中对非英文名称进行排序

java - 数据表中的 Ajax 响应

node.js - 在 Elastic Beanstalk 上使用 Yarn 安装软件包

javascript - 嵌套 setTimeout 不适用于 'this' 变量

javascript - d3.max 没有得到正确的值

javascript - 使用 Json.Net 序列化 Entity Framework 对象

javascript - 如何禁用 hook.io 中的输出

node.js - 在带有 puppet 的虚拟机中使用 Bower 来运行 python-nvd3

javascript - jQuery - 设置和重置转换延迟

javascript - JQuery + setTimeout 不起作用