Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    })
}
like image 240
Scriptomaniac Avatar asked Apr 19 '16 01:04

Scriptomaniac


People also ask

Is forEach slower than for loop?

Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.

Which is the fastest while for forEach () for of?

Correctly used, while is the fastest, as it can have only one check for every iteration, comparing one $i with another $max variable, and no additional calls before loop (except setting $max) or during loop (except $i++; which is inherently done in any loop statement).

Which is faster for loop or forEach?

The foreach loop is considered to be much better in performance to that of the generic for loop.


2 Answers

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.

like image 109
Karl Galvez Avatar answered Oct 28 '22 04:10

Karl Galvez


I make use of the jQuery delay function

Here is a the javascript.

$(document).ready(function(){

  var compSequence = new Array("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

like image 41
Oli Soproni B. Avatar answered Oct 28 '22 03:10

Oli Soproni B.