Async/Await within for loop Javascript.
Tags: javascript
Published: 2021-09-11 07:32:56

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.

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

Here is a demo : [Sliding Game](https://flems.io/#0=N4IgtglgJlA2CmIBcBWAnAOjQGhAZ3gQGMAXeKZEDACxLFhFyIHsA7PZhSl2WAQwAOBCrjxEATpwZIA2gAZscgLq4AZhAR5kM0Kz5hESKrXqMQLVmUuUAPCdgACfqwDmAXgA6IKPC8A+D1YHBzt4PigAoJCDEj4HImo+cQISTxAAVxJVAFoADn9A4OCbEggSBD9S8vgbAHoqisKimxi4vQM0gDcIeAB3AWZxEi94titUr17oEmo3H26ieGypqBnsBwhWMog+WGyxXfg3AEYMOQKo4rFxCAESBzxxIjTaEiEkWtr4VQE+F3gMD5agARACyABkQRCAPrUZgGX7-WqwCAAIyh4OykFYGAAVnh-HVrrcSJFirVqGEIk0bKjmFAAJ5+ByBGnEu7M1msJqqdKsUgQNgPBDwAQOAAUYDwAEoHMAmsFxPASOlxEFWH0HAAFSSQAji8XibDwcTiWVuZnyy5FFIAFQgBmYmUN2Cl0oVDgAvu6op6mk0iPw8HgHAAhZhJKByj0eojBgDChEcbgcAAMPcFUXwiABrFySPlRpAOVGwdLwbqcZUAbgzDkpEBctCQxzkcgEAA9a9bgisZi2253u0UimAki5NsWAExDutEVUccTFgabMjiassnsOVQIDvFuQOA+t9tdutQCB4AT8BlIHfwU9b3aN1jZMrwKXFxaWE3DkcOXHpH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