Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get an animation to play in the order of an array?

Im new to programming and making the infamous Simon says game but I’m having trouble getting the computer generated sequence to animate in the order of the array.

I wanted to have a function that both wiped the previous sequence (assuming the game has started) and creates a new one while animating the buttons in the order of new array. I tried a few different methods but their outputs only confused me more.

var pattern       = []
var userPattern   = [];
var buttonColours = ["red", "blue", "green", "yellow"];
var started       = false
var level         = 0;

function nextSequence() {
  pattern     = [];
  userPattern = [];
  while (pattern.length < 4) {
    var randomNumber = Math.floor(Math.random() * 4);
    var randomColour = buttonColours[randomNumber];
    pattern.push(randomColour);
  }

  /*Method 1*/
  for (i = 0; i < pattern.length; i++) {
    setTimeout(function() {
      $("." + pattern[i]).fadeOut(200).fadeIn(200);
    }, 500 * (i + 1));
  }

  /*Mehtod 2*/
  // setTimeout($("." + pattern[0]).fadeOut(200).fadeIn(200), 500);
  // setTimeout($("." + pattern[1]).fadeOut(200).fadeIn(200), 1000);
  // setTimeout($("." + pattern[2]).fadeOut(200).fadeIn(200), 1500);
  // setTimeout($("." + pattern[3]).fadeOut(200).fadeIn(200), 2000);


  $("h1").html("Level" + " " + level);
  level++;
  console.log(pattern)
}

The first method doesn’t play the animation at all and the second plays the animations simultaneously completely disregaurding the setTimeout function. Method 2 also returns a Uncaught SyntaxError: Unexpected identifier ‘Object’ directed at all 4 lines of code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the first method you are passing a function as parameter to the setTimeout which is fine, but by the time the i in the function gets evaluated it is already i = 4.

The way to overcome the late evaluation of the i is to pass a copy of it to a scope containing it. It’s simpler than it’s sound.

/*Method 1*/
for (i = 0; i < 4; i++) {
  (function(i) {

    setTimeout(function() {
      $("." + pattern[i]).fadeOut(200).fadeIn(200);
    }, 500 * (i + 1));
    
  })(i)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading