如果满足特定条件,我想延迟调用我的 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
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/