我想在我的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