Using forEach or a forLoop, how do you run the callback on each element with a 1second delay between each?

时间:2017-10-12 09:53:33

标签: javascript arrays foreach

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)
    })
  }

0 个答案:

没有答案