Simon Game Project - Sounds & Playback timing issues

Simon Game Project - Sounds & Playback timing issues
0

#1

Hey Coders,

I’m happy with the general functionality of my Simon Game, but when it goes to play back the array of computer outputs it plays them simultaneously rather than one after another. I’ve put in asynchronous timing methods in place, but they aren’t working within the for-loop that I’ve made (see below), can anyone suggest another way I could approach this issue?

I believe that the for loop iterates through each output without delay, and each output has it’s own 1000ms delay - but because they’re all executed at the same time, after that 1000ms they run together. I tried to find something to put after the setTimeout… which would basically be a ‘wait x seconds’ but everywhere seems to point to asynchronous timing events. Is there a ‘wait’ method OR a way to make asynchronous events work properly when iterating through an array?

for (var i = 0; i < simonArr.length; i++) {
    setTimeout(output(simonArr[i], 1000));
  }

Here’s a link to my codepen: https://codepen.io/antiaccess/pen/wogRwp

Thanks for reading! If you can offer any help or direct me to some resources it would be much appreciated

Best,
Ant


#2

Hi Antiaccess.
I found this code (posted by “cji” on stackoverflow.com) to be the best when confronting that same problem:

var i = 0, howManyTimes = 10;
function f() {
    alert( "hi" );
    i++;
    if( i < howManyTimes ){
        setTimeout( f, 1000 );
    }
}
f();

Obviously you are going to have to tailor it to your needs, but, for me, instead of the “alert(“hi”);” line, that is where you could put a function call to whatever you need to occur every second.
Best of luck.


#3

Hey Richard,

thanks for the idea of recursion, it ran through my mind but it was one of those days where my brain wasn’t cooperating. Thanks for the push, the code now works ideally!

Cheers mate!