I wrote this function to show flashing lights for a simon game that I’m making. The flashing part is working, but I’m trying to play a sound everytime move.color.backgroundColor === colors[0], which is the highlighted color. The array is being looped over too fast for me to do this and I’ve been getting several different errors trying to solve this different ways, including all the sounds going off before the flashing has finished because the for loop variable finished looping faster than the variables showed flashing and then breaking the flashing function, even though its supposed to go at 1 second per loop. Here is the code -
game.computerMoves = {green, blue, blue, red, red, yellow};
const colors = [
new Map([[green, "lime"], [yellow, "#FF6"], [blue, "dodgerblue"], [red, "salmon"]]),
new Map([[green, "green"], [yellow, "#CC0"], [red, "red"], [blue, "blue"]])
];
const sounds = {
green : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"),
blue : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"),
yellow : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"),
red : new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3")
};
game.computerMoves = {green, yellow, yellow, blue, red, red};
const colorFlashPeriod = 1000; // in ms
function showMoves() {
let moveCounter = 0;
const timeoutCount = game.computerMoves.length * 2;
(function nextColor() {
//this variable was finished looping before the backgroundColor finished flashing and it incremented faster than 1 second per loop. The flashing was shown at the correct times though, but I can't use this to set keys to add sounds
let move = game.computerMoves[moveCounter >> 1];
let c = game.computerMoves[moveCounter]
console.log(c.id);
move.style.backgroundColor = colors[(moveCounter++) & 1].get(move);
if (moveCounter < timeoutCount) { setTimeout(nextColor, colorFlashPeriod) }
})();
}
I also rewrote the showMoves function to flash lights into a working version here
function showMoves() {
let i = 0;
const start = setInterval(function() {
if (i >= game.computerMoves.length) {
clearInterval(start);
return;
}
const move = game.computerMoves[i];
setLight(move, true);
setTimeout(setLight.bind(null, move, false), 1000); //Using bind to preset arguments
i++;
}, 2000);
}
function setLight(color, isOn) {
if(isOn){
sounds[color.id].play();
}
color.style.backgroundColor = isOn ? colors[0].get(color) : colors[1].get(color);
}
This version of is working how I want it to and playing the sounds at the right flashing times, but I’m not sure if its better designed than the showMoves function above it that I can’t figure out how to get the sound to work on. I would appreciate any help with this.