user18227353
user18227353

Reputation:

JS timeout in for loop

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 -->

Upvotes: 0

Views: 422

Answers (2)

vitaly-t
vitaly-t

Reputation: 25890

When processing an iterable, like coffeeMachine.shoppingCard.list in your example, it is more efficient to process it as such...

The example below makes use of iter-ops library:

import {pipeAsync, delay} from 'iter-ops';

const i = pipeAsync(
                     coffeeMachine.shoppingCard.list,
                     delay(a => a.time * 1000)
                   ); //=> AsyncIterable

// process your list:
for await (const a of i) {
    console.log('value:', a);
}

Upvotes: 0

Keith
Keith

Reputation: 24211

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();

Upvotes: 2

Related Questions