簡體   English   中英

在forEach循環中使用setTimeout

[英]setTimeout in forEach loop

如果要滿足特定條件,我想延遲在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秒后運行等等

var index = 1;
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)
                }
            }, (index)*5000);
            index++;
        }        
    }) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM