-2

My code is :

for (let i = 0; i <= 5; i++) {
  delay(i);
}

function delay(i) {
  setTimeout(() => console.log(`${i} is the number`), 2000);
}

The output i am getting after 2 second is :

0 is the number

1 is the number

2 is the number

3 is the number

4 is the number

5 is the number

They all print together immediately after 2 second , while I want each of them to print after 2 second for eg :

0 is the number

(after 2 second)

1 is the number

(after 2 second)

2 is the number .....

Is there any way to make it work? Thank you!!

adiga
  • 34,372
  • 9
  • 61
  • 83
001Wolf
  • 26
  • 1
  • 6

1 Answers1

0

setTimeout is a non-blocking function. The for loop doesn't wait for delay to be finished, but just calls delay(i) six times in a row directly.

To make this case work, you could use async/await and Promise-ify setTimeout:

(async () => {
for (let i = 0; i <= 5; i++) {
    await delay(i);
}
})();

function delay(i) {
return new Promise(resolve => setTimeout(() => {
    console.log(`${i} is the number`);
    resolve();
}, 2000));
}
fjc
  • 5,590
  • 17
  • 36