Simon Buttons - same code? Different results

Simon Buttons - same code? Different results
0.0 0

#1

Hey guys. Working on my Simon Game, so close to that front-end cert I can almost taste it!

Right now I have something that almost works totally as intended. In fact, it’s half-correct. My green and blue buttons turn on and off as I intended, and respond correctly to the user clicks. But the yellow and red buttons, when they light up, stay lit and ruin the sequence. On line 116 of the JS code, you’ll notice I have a commented out command to make my sequence all 1 instead of an array of random numbers from 1-4. When I do this, only the green button lights up and the user is able to click through all the way to the end of the game. Obviously this isn’t very exciting. And I’m pretty sure I have the same code for all of my buttons, so why do two of them work and two of them don’t? I’d love it if someone could take a look. Here is a link to my pen. Thanks much!


#2

Hey everyone, quick update. I’ve been throwing some console.log’s into the code to try and test where it goes wrong. If, on line 30 or so, where the code determines that if green is the next button that should light up, I can add a little console.log('green on'); , followed by console.log('green off'); in the following setTimeout function, and they are logged appropriately. But if I try to do the same within the red or yellow buttons, it’s becoming clear that only the first line of code will be executed over and over and over, and it won’t ever get to the setTimeout function, or even play the corresponding sound. To clarify:

//random is my array of numbers from 1-4, generated randomly, which
//determines the order of the buttons which the user must match.
//j is a counter that increments to iterate through that array.
   if (random[j] == 1){
      $('#0').addClass('green-lit');
      $('#audio1')[0].play();
      litID.push(1);
      
      setTimeout(function(){
        $('#0').removeClass('green-lit');
      }, off);
    }
    else if (random[j] == 2) {
      //this console log and the following addClass command just repeat forever
      console.log('red on');
      $('#1').addClass('red-lit');
      //this audio never gets played
      $('audio2')[0].play();
      litID.push(2);
      
      //so I think I can safely presume that the code never reaches this 
      //setTimeout function
      setTimeout(function(){
        $('#1').removeClass('red-lit');
        console.log('red off');
      }, off);
    }