Kane Kane - 6 months ago 21
Javascript Question

Change appearance of elements based on sequence stored in array

I have two quarters of a circle in two span tags:

<div>
<span id="topleft"></span>
<span id="topright"></span>
</div>

<button id = 'clickme' style = 'margin-top: 100px;'>CLICK ME</button>


When I click the button I want the divs to 'light up' based on a sequence stored in an array using JavaScript:

let reset = (position) => {
document.getElementById(position).style.opacity = 1;
};

let blink = (position) => {
document.getElementById(position).style.opacity = 0.5;
};

let sequence = (positions) => {

let currentBlink = positions.pop();
blink(currentBlink);
setTimeout(reset.bind(null, currentBlink), 1000);

if (positions.length > 0) {
sequence(positions);
}

}

document.getElementById('clickme').onclick = () => {
sequence(positions);
}

let positions = ['topleft', 'topright'];


The problem is that both divs 'light up' at the same time where I actually want a pause between the two.

How can I achieve this effect?

Thanks any help appreciated.

Answer

Invoke the function after timeout in callback.

let reset = (position) => {
  document.getElementById(position).style.opacity = 1;
};

let blink = (position) => {
  document.getElementById(position).style.opacity = 0.5;
};

let sequence = (positions) => {
  let currentBlink = positions.pop();
  blink(currentBlink);
  setTimeout(function() {

    reset(currentBlink);
    if (positions.length > 0) {
      sequence(positions);
    }
  }, 1000);
}

document.getElementById('clickme').onclick = () => {
  sequence(positions);
}

let positions = ['topleft', 'topright'];
<div>
  <span id="topleft">aaa</span>
  <span id="topright">aaa</span>
</div>
<button id='clickme' style='margin-top: 100px;'>CLICK ME</button>

Fiddle Demo