0

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Based on the output the OP wants it should be i + 1.
OP here's some documentation for async/await.
@Andy yeah, I just copied the OP's code here, I've updated so it's more like the OP's output..
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.