DEV Community

artydev
artydev

Posted on

Async/Await within for loop Javascript.

It's perfectly possible to use await in a for loop. In the following code, I use a sleep function, in order to slowdown the shuffle of an array.

  async shuffle () {
      for (let i = 0; i < 200; i++) {
        const emptyCellPos = Number(this.emptyCell.dataset.curpos); 
        const leftPos = emptyCellPos - 1;
        const rightPos = emptyCellPos + 1;
        const upPos  = emptyCellPos - 4;
        const downPos = emptyCellPos + 4;
        const validPos = [leftPos,rightPos,upPos,downPos].filter(pos => {
          return (pos >= 0) && (pos <= 15) 
        }) 
        const randomPos= validPos[Math.floor(Math.random()*validPos.length)];
        await sleep(1)
        this.moveCellByCurpos(randomPos)  
      }
    }
Enter fullscreen mode Exit fullscreen mode

Here is a demo : Sliding Game

Discussion (0)