Skip to content Skip to sidebar Skip to footer

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 everyt

Solution 1:

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.

Solution 2:

I make use of the jQuery delay function

Here is a the javascript.

$(document).ready(function(){

  var compSequence = newArray("red", "blue", "yellow");

  var displaySequence = function() {

      $.each(compSequence, function (i, color) {
        // add delay
        $("#" + color).delay(i * 1000).fadeTo(300, 0).fadeTo(300, 1.0);
      });      
  }

  displaySequence();

});

Here is a DEMO

Post a Comment for "Delay Between Each Iteration Of Foreach Loop?"