0

I'm trying to program some buttons to light up and play a sound in the order of numbers from a random array I've generated, I'm changing the color to a lighter color than changing it back to the original in order to make them light up. Some of the time this works and then some of the time the buttons don't go back to the original color and I'm not sure why, I can't find a pattern to it. Can anyone see what I'm doing wrong with my code?

var  turn = 19;
var b = 0;  
 function flash(button, light) {
button.addClass(light).delay(500).queue(function(){button.removeClass(light);})
  } 

  function lightUp() {
switch (game[b]) {
  case 1:
    one.play();
    flash($("#1"),"onelit");
    break;
  case 2:
    two.play();
    flash($("#2"),"twolit");
    break;
  case 3:
    three.play();
    flash($("#3"),"threelit");
    break;
  case 4:
    four.play();
    flash($("#4"),"fourlit");
    break;
}

b++;
if (b < turn) {
  setTimeout(lightUp, 2000);
}
  }
Keli
  • 63
  • 2
  • 8
  • OK so it seems to be only executing the function after the delay once, and then the second time each button lights up it doesn't go back to the original color – Keli Feb 17 '17 at 18:04
  • Your problem might be that you are not calling `next()`, like in [this answer](http://stackoverflow.com/a/2510255/859640). BTW, You should really avoid using a switch statement like that. Here's a [jsfiddle](https://jsfiddle.net/31bb0azk/1/) that might give you some ideas. – John S Feb 17 '17 at 23:23
  • Thank you the next() solved it! Is a switch statement like that just clunky? – Keli Feb 21 '17 at 17:25
  • Each case in the switch statement is doing the same thing, just to a different button. That is repetitive code, and it makes it harder to add another button. Here's a new [jsfiddle](https://jsfiddle.net/31bb0azk/2/) with one more button. It adds another div in the html, and some CSS styles, but the only change in the JavaScript is the addition of another object in the array. – John S Feb 21 '17 at 23:08

1 Answers1

1

The JQuery documentation for the .queue() function shows that the callback function is passed a function that when called "will dequeue the next item". You should call that function at the end of your callback. (BTW: It is common to name the parameter "next".)

function flash(button, light) {
    button.addClass(light).delay(500).queue(function(next) {
        button.removeClass(light);
        next();
    });
} 

Thanks to this answer.

Community
  • 1
  • 1
John S
  • 21,212
  • 8
  • 46
  • 56