This question already has an answer here:
setTimeout/Loop… still confused
                                
                                    (1个答案)
                                
                        
                2年前关闭。
            
        

我有以下代码:

myList = [["one", "two", "three"], ["uno", "dos", "tres"], ["1","2","3"]]

    myList.forEach(function (subList) {
        setTimeout(function () {
            console.log(subList);
        }, 5000);
    });


我认为每5秒,这应该输出myList的每个元素,但是,而不是对其进行迭代,只需等待5秒,然后一次输出三个子列表。

我该怎么做,所以它会做一个子列表,然后等待5秒钟,然后再下一个...

最佳答案

你必须做



myList = [["one", "two", "three"], ["uno", "dos", "tres"], ["1","2","3"]]

    myList.forEach(function (subList, i) {
        setTimeout(function () {
            console.log(subList);
        }, 5000*(i+1));
    });





以来

    setTimeout(function () {
        console.log(subList);
    }, 5000);


表示它将在至少5000ms之后打印subList,所有事件将在5000ms之后调用


  5000 *(i + 1)将确保在5000ms,10000ms,15000ms之后被调用...

08-05 02:13