Search code examples
javascriptfor-loopwebdelay

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

Solution

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