Simon game problem

Simon game problem
0.0 0

#1

can anybody help me with a function,the one named fire_all_boxes,it should play sounds one after the other,instead of that it plays all the sounds at the same time,here is the codepen https://codepen.io/mehdij/pen/mxVpBa


#2

First of all, I’ll just point out the javascript convention that fire_all_boxes should be fireAllBoxes - it may seem silly, but it will get you some odd looks in the JS community.

As for your problem:

  1. fire_all_boxes gets called 20 times every time the button is pushed because it’s called inside a for loop. Why?
  2. Each box is called one at a time. It is turned black and then a timeout is set to turn it back to it’s regular color at 2 seconds in the future. And then (and this is really important) javascript does not wait but moves onto the next thing. Many programming languages are synchronous - they wait for each thing to get done before moving onto the next. JS does not do that. It has a task to do in 2 seconds but just keeps working on other things until that 2 seconds is up. JavaScript is asynchronous, This is an important concept. It’s frustrating at first, but there are many advantages to this in a web environment. In order to get the buttons to do what you want, you’re going to have to not just set up a timeout for when you want the button to turn back but when you want it to turn on, a cascade of setTimeout functions with calculated delays. Time to do some math.
  3. On line 18, you would be better served with a switch statement. Anytime you have a chain of if/else statements checking for different equalities, then a switch statement is called for.
switch (num_box) {
  case 1:
    // code here
    break;
  case 2:
    // code here
    break;
  case 3:
    // code here
    break;
  case 4:
    // code here
    break;
  default:
}