0

I want to run a function every second for each element in an array, however I have been unable to figure it out. My code is below.

Basically I'm wanting to run this.activeButton() every second for each element in the array. It was suggested to wrap this.activeButton() to run every second, however it simply runs the function on all of the elements in the array after 1 second instead of running the function every second for EACH element in the array.

  drawComputerMoves(moves) {
    moves.forEach((move) => {    
      let buttonRef = 0;
      switch (move) {
        case 1:
          buttonRef = 'greenBtn'
          break;
        case 2:
          buttonRef = 'redBtn'
          break;
        case 3:
          buttonRef = 'blueBtn'
          break;
        case 4:
          buttonRef = 'yellowBtn'
          break;
        default:
          break;
      }
      setTimeout(() => this.activeButton(buttonRef), 1000)
    })
  }
Nims
  • 195
  • 2
  • 2
  • 11
  • Use `setInterval` function. – Hasan Shahriar Oct 12 '17 at 09:55
  • Wrap it in `setInterval`. – Walk Oct 12 '17 at 09:55
  • Also, instead of that whole `switch`, you can use `let buttonRef = ['greenBtn','redBtn','blueBtn','yellowBtn'][move-1] || 0` – Cerbrus Oct 12 '17 at 09:56
  • Hey @Cerberus, what technique or method is this? It looks more simple, however I do not understand it. Cheers. – Nims Oct 12 '17 at 09:59
  • 1
    @Nims, the first part is just an array, where you take the element at index `move-1`. For example: `['a','b','c'][1]` returns `b`. The `|| 0` is for the `default` case, where the `move` is out of range of the array. Then the `[][]` returns undefined, `|| 0` makes sure a default value is returned. For example: `['a','b','c'][7] || 0`. – Cerbrus Oct 12 '17 at 10:02
  • @Cerberus, thanks! – Nims Oct 12 '17 at 10:06
  • BTW which part of the above function am a wrapping with setInterval? – Nims Oct 12 '17 at 10:07
  • @Walk, which part should I be wrap with setInterval? Thanks :) – Nims Oct 12 '17 at 10:15
  • @Nims `this.activeButton(buttonRef)`, so it will look like `setInterval(() => { this.activeButton(buttonRef) }, 1000);` – Walk Oct 12 '17 at 10:27

0 Answers0