As part of a Simon game, I want to animate(background change using css) the span tags sequentially.
function animateGeneratedPattern(){
//alert(generatedPattern);//pattern generated randomly in advance.
var i=0;
while(i<generatedPattern.length){
switch(generatedPattern[i]){
case 1:
animateRed();
setTimeout(animateRed,500);
break;
case 2:
animateGreen();
setTimeout(animateGreen,500);
break;
case 3:
animateBlue();
setTimeout(animateBlue,500);
break;
case 4:
animateYellow();
setTimeout(animateYellow,500);
break;
}
i++;
}
}
For each appropriate color, I am using this type of function to toggle between backgrounds:
function animateYellow(){
$("#4").toggleClass("animateYellow");
}
I have managed to change the background, but all the spans change color at the same time. What do I change to make it sequential rather than at the same time??
Full Code Here: http://codepen.io/jpninanjohn/pen/JKoYqR?editors=1010
The issue is that the while loop runs through each of the animation functions almost instantaneously, with the same 500ms delay. Using the same i variable, we can stagger those. Here's an updated codepen: http://codepen.io/thecox/pen/ezmVEy?editors=1010
Basically, just update each of the switch statements to multiply the delay by the iteration of the loop:
setTimeout(animateRed,500 * i);
Adjust the delay length, as needed. Let me know if that makes sense.
Your implementation uses generatedPattern as an array rather than a queue. To use it as a queue, operate only on element [0], then splice off element [0] before the next iteration. Each iteration sets up the next iteration after it has executed. For example, try this:
function animateGeneratedPattern() {
function animateNextPattern(lightup) {
if (!generatedPattern || generatedPattern.length === 0) {
return;
}
switch(generatedPattern[0]) {
case 1:
animateRed();
break;
case 2:
animateGreen();
break;
case 3:
animateBlue();
break;
case 4:
animateYellow();
break;
}
if (lightup) {
// Long delay before turning light off
setTimeout(function() {
animateNextPattern(false);
}, 500);
}
else {
generatedPattern.splice(0, 1);
// Small delay before turning on next light
setTimeout(function() {
animateNextPattern(true);
}, 10);
}
}
animateNextPattern(true);
}
JSFiddle of this here using your CSS and HTML showing the animation working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With