Home > OS >  JS timeout in for loop
JS timeout in for loop

Time:10-11

I want to print something and set a timeout for the next iteration. for example: 1 --> 2s delay --> 2 --> 2s delay --> 3 --> ...

 for (let i = 0; i < 10; i  ) {
       console.log("index: "  i);
        setTimeout(() => {
        }, coffeeMachine.shoppingCard.list[i].time * 1000);
    }
}

This would print:

0,1,2,3,4,5,6,7,8,9 --> 2s delay

But I want this:

 1 --> 2s delay --> 2 --> 2s delay --> 3 -->

CodePudding user response:

Modern JS has something called async / await.

If you wrap a setTimeout into a Promise constructor you can fake a delay, and use await delay(ms) on this Promise.

As mentioned in comments, MDN has some good docs on async / await -> MDN Docs

eg.

const delay = ms => new Promise(r => setTimeout(r, ms));

async function test() {
  for (let i = 0; i < 10; i  ) {
    console.log("index: "  (i   1));
    await delay(2000);
  }
}

test();

  • Related