且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

forEach循环中的setTimeout

更新时间:2022-04-13 15:46:57

正如其他人所提到的,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