change setTimeout function to make the for loop print in ascending order

Viewed 73

function randomNum(){
    let data;
    for(let i=1;i<=10;i++){       
        let time = Math.random()*100;
        setTimeout(()=>console.log(i,time),time)
    }
}
randomNum();

For Each iteration, the program needs to stop for random time, then i should be printed and the loop continued

1 Answers

function randomNum() {
  let timeToWait = 0; // here
  for (let i = 1; i <= 10; i++) {
    let time = Math.random() * 100;
    timeToWait += time; // here
    setTimeout(() => {
      console.log(i, time);
    }, timeToWait); // update here. Updated
  }
}
randomNum();

async function randomNum2() {
  for (let i = 1; i <= 10; i++) {
    let time = Math.random() * 100;
    await new Promise((resolve) => {
      setTimeout(() => {
        console.log(i, time);
        resolve();
      }, time);
    })
  }
}

randomNum2();

You have to calculate time to wait for the next time.

In this case, in "next" time of the loop, time need to wait is total time to wait of before times.

Update the way using async/await.

Related