Q:

javascript setTimeout function doesn't work inside a loop

I'm making a Simon Game and I'm trying to make the button presses have 1 second interval. But It seems that my setTimeout function is not doing its job and all clicks are performed at once without the 1s interval. I tried alerting something outside the loop and it works just fine. Can anyone help me with this?
This is my JavaScript code:
    for (var count = 1; count <= 20; count++) {
      $("#count").html(count);
      seq.push(Math.floor(Math.random() * 4));
      seq.forEach(function(press) {
        setTimeout(function() {
          eval('$("#button' + press + '").click();');
        }, 1000);
      });
    }

and the corresponding html:
    <p>count: <span id="count">0</span></p>

    <button id="button0" onclick="sound1.play()"></button>
    <button id="button1" onclick="sound2.play()"></button>
    <button id="button2" onclick="sound3.play()"></button>
    <button id="button3" onclick="sound4.play()"></button>

Thank you!

A:

The problem is the way you do setTimeout.
The for loop iterates within a few milliseconds and you basically request all the clicks to run one second later, so they all happen one second later but at the same time.
If you request the first click after one, the second click after two seconds and so forth, you'll get what you want:
  seq.forEach(function(press, i) {
    setTimeout(function() {
      $("#button" + press).click();
    }, 1000 * i);
  });

Also note that you probably want to restructure your code to not do this twenty times over:
for (var count = 1; count <= 20; count++) {
  $("#count").html(count);
  seq.push(Math.floor(Math.random() * 4));
}

seq.forEach(function(press, i) {
  setTimeout(function() {
    $("#button" + press).click();
  }, 1000 * i);
});

