2

I am replicating a simon game prototype and I am trying to write a function for a button blink in vanilla js.

Currently I have the following function:

function blinkColor(color) {
  let colorButton = document.getElementById(color);
  colorButton.style.background = *highlightColor*;  
  setTimeout(() => {colorButton.style.background = *originalColor*}, 1000);
}

I am replacing the buttons color with another brighter color and then changing it back again with a timeout. It works when the consecutive colors are different from each other but when it needs to blink the same color more then once (e.g 'red', 'red', 'red'), it does not leave a break in between the blinks and it looks like it is just making one long blink.

Is there a better way to write this functionality?

Jens Põldme
  • 23
  • 1
  • 3

2 Answers2

2

You can compare the color and use a default one when the highlighted color is the same as the current color:

function blinkColor(color) {
  let colorButton = document.getElementById(color);
  colorButton.style.background = *highlightColor*;
  if(highlightColor == colorButton.style.background){
    setTimeout(() => {colorButton.style.background = *white(i.e.)*}, 1000);
  } else {
    setTimeout(() => {colorButton.style.background = *originalColor*}, 1000);
  }
}

You have to perform your comparison to check the type of color (rgb, rgba, hex...) and if you have the possibility to use css-animation for that, just do it :-)

Marouen Mhiri
  • 1,640
  • 1
  • 14
  • 20
0

The relevant code isn't actually in your question.

It sounds like there are three events you need to care about:

  1. A colour is highlighted
  2. A colour is dimmed
  3. The next colour is highlighted

Your problem is that the time between 1 and 2 is the same as (or less than) the time between 1 and 3 (1 second).

You need to increase the time between 1 and 3 so that the colour can be dimmed before it is highlighted again. 1.25 seconds would probably be a good choice.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • @JensPõldme — That doesn't change this answer. You still need to make the time between turning each light on more than the time between turning a single light on and then turning the same one off again. (e.g. change `1000*i` to `1250*i` – Quentin Sep 20 '17 at 11:47
  • Thank you for your answer! I should have specified that the function above is a callback in another settimeout that is called for every color in an array. I increased the time for this function and it did the trick. – Jens Põldme Sep 20 '17 at 11:50