forEach循环中的setTimeout [英] setTimeout in forEach loop

查看:1217
本文介绍了forEach循环中的setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to delay making a call to another function in my forEach loop if a certain condition is met, but am not understanding setTimeout in this scenario.

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秒

I would like a 5 second delay each time I need to call 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秒后,所有都在相同时间运行。

As others have mentioned, setTimeout is async, so js fires on the forEach all timeouts funcions, with a wait time of 5 seconds. So after 5 seconds, all run at the "same" time.

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

To avoid this, you could either do a queue and run just one timeout and when you finish call the next one, or in this case a simpler solution would be to just adjust the wait time according to the index of the person you are iterating:

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等等

This way, first one will run after 5 seconds, second one after 10, third one 15 and so on

这篇关于forEach循环中的setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆