Help with timeout loop for Simon game!

Help with timeout loop for Simon game!
0.0 0

#1

Hello friends,

I’m trying to write a function that will display all of the colors in the current pattern of a game of Simon. The function should be timed in that it will display one color every couple seconds. However, the function is not working. Instead of iterating through the pattern, it just turns on all the colors in the pattern at once. Here’s the code I have so far:
// This function displays all of the colors in the current pattern.
function displayPattern() {
for (var i = 0; i < currentPattern.length; i++) {
setTimeout(lightColor(currentPattern[i]), (i * 2000) + 1000);
}
}

function lightColor(color) {
// code to “light up” the chosen color
}

I know that the lightColor function works because I can see that the colors. Any ideas what I’m doing wrong?


#2

I believe the way your setTimeout is structured, the lightColor is being called immediately, try this.

setTimeout(function() {lightcolor(currentPattern[i])}, (i * 2000) + 1000);


#3

That doesn’t seem to be the solution.

I now have the following code:
function displayPattern() {
for (var i = 0; i < currentPattern.length; i++) {
console.log("First I = " + i);
setTimeout(function() {
console.log("Second I = " + i);
lightColor(currentPattern[i]);
}, 1000);
}
}

When I look at dev tools, I see the following:
First I = 0
Second I = 1

In other words, the value of i has changed between the time it is called before I set the timeout function, and the time when the function actually executes. How can I preserve the value of i until it is ready to be called?