I'm working on a Simon Says program and I am running into issues with calling the computer's series of moves and displaying them on the screen.
I am attempting to use this aiMoves() function to iterate through the array and display each move by highlighting the appropriate color button. I am attempting to use setInterval so that the first button highlights, the program waits a second, then the next button highlights like so:
function aiTurns(randNum){
for(var i = 0; i < aiMoves.length; i++) {
if(aiMoves[i] === 1){
//sound1();
$('#green').addClass("active");
setTimeout(function(){
$('#green').removeClass("active");
}, 500);
}
else if(aiMoves[i] === 2){
//sound2();
$('#red').addClass("active");
setTimeout(function(){
$('#red').removeClass("active");
}, 500);
}
else if(aiMoves[i] === 3) {
//sound3();
$('#yellow').addClass("active");
setTimeout(function(){
$('#yellow').removeClass("active");
}, 500);
}
else if(aiMoves[i] === 4){
//sound4();
$('#blue').addClass("active");
setTimeout(function(){
$('#blue').removeClass("active");
}, 500);
}
level--;
playerTurn = true;
}
}
I called it like this:
var moves = function() {
aiTurns(randomNumber());
}
setInterval(moves, 2000);
}
The problem is setInterval is asynchronous and all iterations of the for loop within aiMoves() are called at the same time. How can I set this up so that the first element of the array executes, it pauses, then the next elements executes?
Here is the codepen for a better visualization: https://codepen.io/nick_kinlen/pen/oGjMMr?editors=0010