I am making a Simon-style game and I can get the animation to play the last color in the pattern, but it won't play the entire pattern. I've tried a couple of different things:
function nextTurn() {
patternComputer.push(getNextColor());
for (i = 0; i < patternComputer.length; i++) {
setTimeout(function() {
animateColor(patternComputer[i]);
playSound(patternComputer[i]);
}, 500);
}
patternPlayer.length = 0;
}
This one runs through the for loop but doesn't go into the setTimeout function at all until the time has passed, but by then, i
isn't correct. I have also tried taking it out of the setTimeout entirely, but that of course makes every animation and sound play at once. How can I make it animate and play the sound of patternComputer[0] and then wait half a second and then play patternComputer[1] and then wait half a second and then play patternComputer[2]...etc. I can't figure out how to just pause the code and let it slowly cycle through each iteration. Is this possible? Should I find a different solution? Thanks! :)
Note that javascript runs in a single thread using the Event Loop.
The problem here is you are registering n timeouts that will be run 500 ms after the main thread registers them. They all will run almost at the same time once those 500 ms pass.
In order to fix your code and make them run 500ms separated you will need to call back your code from the setTimeout. Another simpler solution (but not ideal) would be something like this:
for (i = 0; i < patternComputer.length; i++) {
setTimeout(function() {
animateColor(patternComputer[i]);
playSound(patternComputer[i]);
}, 500 * (i+1));
}