javascript - forEach 循环中的 setTimeout

标签 javascript node.js

如果满足特定条件,我想延迟调用我的 forEach 循环中的另一个函数,但我不理解这种情况下的 setTimeout。

function checkName(person) {
    console.log('checking name of ' + person.name)
    if (person.name === 'Julie') return true 
}

function checkPersons() {
    var persons = [
        {name: 'Bob', age: 21},
        {name: 'Frank', age: 15},
        {name: 'Julie', age: 12}
    ]

    var results = []

    persons.forEach(function(person) {
        if (person.age >= 18) {
            console.log('do not need to check name of ' + person.name)
            results.push(person)
        } else {
            setTimeout(function() {
                if (checkName(person)) {
                    console.log('Julie is ' + person.name)
                    results.push(person)
                }
            }, 5000)
        }        
    }) 
}

checkPersons()

https://jsfiddle.net/nicholasduffy/sy7qpqu1/1/

我明白了

do not need to check name of Bob
// 5 second delay here
checking name of Frank
checking name of Julie
Julie is Julie

每次我需要调用 checkName

时,我希望有 5 秒的延迟
do not need to check name of Bob
// 5 second delay here
checking name of Frank
// 5 second delay here
checking name of Julie
Julie is Julie

最佳答案

正如其他人提到的,setTimeout 是异步的,因此 js 在 forEach 所有超时函数上触发,等待时间为 5 秒。所以 5 秒后,所有的都在“同一”时间运行。

为了避免这种情况,你可以做一个队列,只运行一个超时,当你完成调用下一个时,或者在这种情况下,一个更简单的解决方案是根据你的人的索引调整等待时间正在迭代:

persons.forEach(function(person, index) { // we add index param here, starts with 0
    //your code
    else{
        setTimeout(function() {
            if (checkName(person)) {
                console.log('Julie is ' + person.name)
                results.push(person)
            }
        }, 5000*(index+1)) // or just index, depends on your needs
    }        
}) 

这样,第一个将在 5 秒后运行,第二个将在 10 秒后运行,第三个将在 15 秒后运行,依此类推

关于javascript - forEach 循环中的 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34316616/

相关文章:

Javascript - 无法遍历带有图像的对象数组

javascript - 如何在 Express 中获取响应正文?

javascript - 解析json并写入文件

javascript - Passport.js 登录错误

javascript - 为什么我在 indexOf 中用 JavaScript 找不到斜杠?

javascript - firebase是否支持数组查询?

javascript - 等待 jQuery 在 Wordpress 中加载

node.js - 创建一个单元测试两个检查两个 psql 模式是否相同

node.js - 我在服务或部署 Firebase 托管功能时遇到问题

javascript - 如何在网页中的谷歌地图上添加标记