Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!