Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

javascript - Delay between each iteration of foreach loop?

so I am making a simon says game. This function displays the current sequence. The problem with it right now is that it doesn't really go in a nice sequence, it kind of does everything at once. Say the colors are "blue", "red", and "yellow, they will all go off at the same time rather than in sequence. How can I fix this?

var displaySequence = function(){
    compSequence.forEach(function(color){
        $("#" + color).fadeTo(300, 0.5).fadeTo(300, 1.0);
    })
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A none jQuery solution. You will need to use the array index to give the illusion of waiting between each call, however each function has ran already. What will happen is: show color 1 in 1 second, show color 2 in 2 seconds...

var displaySequence = function(){
    compSequence.forEach(function(color, index){
        setTimeout(function(){
            $("#" + color).fadeTo(300, 0.5).fadeTo(300, 1.0);
        },
        1000 * index);
    })
}

adjust the 1000 * index to change the delay.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...