Search code examples
javascriptasync-awaitpromisedelay

How to run the same JS function multiple times and wait until the previous has finished?


I have a function that I need to run multiple times but wait until the previous one has finished.

Currently What I have is:

for(var x = 0; x < rollsArr.length; x++){
    rollDice(data.results, x)
}

function rollSkins(results, rollN) {
    // do some stuff

    setTimeout(function() {
        roll(results, rollN)
    }, 500);
}

function roll(results, rollN) {
    // do some stuff

    setTimeout(function() {
        // do some stuff
    }, 8500);
}

I would like a roll function to finish then wait a few seconds and then start another roll. I tried awaiting rollDice but I didn't implement it correctly or it did not work.

What would be the solution for this?


Solution

  • You can use async/await or Promise.then(). Reference: https://zellwk.com/blog/async-await-in-loops/

    const rollsArr = [1,2,3];
    const data = {results: "example"};
    
    const sleep = ms => {
      return new Promise(resolve => setTimeout(resolve, ms))
    }
    
    (async () => {
      for (var x = 0; x < rollsArr.length; x++){
          await rollDice(data.results, x)
      }
    })()
    
    async function rollDice(results, rollN) {
        // do some stuff
    
        await sleep(500);
        await roll(results, rollN);
    }
    
    async function roll(results, rollN) {
        // do some stuff
        console.log("Rolling dice");
    
        await sleep(1000);
        console.log("Doing stuff");
    }