0

Whenever I am running my code, it stops working after a few iterations.

function wait(delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("");
    }, delay);
  });
}
let t = 0;
async function n() {
  while (t < 10) {
    let i = t + 3;
 console.log("i < 5 ?",i,i<5)
    while (i < 5) {
      console.log("starting i...");
      await wait(800);
      console.log(i);
      i++;
    }
    let u = t + 4;
 console.log("u< 5 ?",u,u<5)
    while (u < 5) {
      console.log("starting u +...");
      await wait(800);
      console.log(u);
      u++;
    }
    t++;
  }
}
n();

Output:

     starting i...
     3
     starting i...
     4
     starting i +...
     4
     starting i...

Does somebody see an error in my code?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156

1 Answers1

0

Your first while loop doesn't await anything and will be executed directly.

then, you wrote

let i = t + 3; // First iteration == 4, second == 5
console.log("i < 5 ?",i,i<5)
while (i < 5) {
 // ...
}

But i will be, at the second loop, equal to 5 -> it wont run anymore, and the same for the u.

So it will only run one, same as to say that your first while is kind of useless.

You could provide more information if the answer didn't helped you, and I'll enhance it.

Response to the comment bellow

can I make my first loop wait for completing the inner 2 while loops?

function wait(delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('')
    }, delay)
  })
}
let t = 0
async function n() {
  while (t < 10) {
    let i = t + 3
    console.log('i < 5 ?', i, i < 5)
    ;async () => {
      while (i < 5) {
        console.log('starting i...')
        await wait(800)
        console.log(i)
        i++
      }
    }
    let u = t + 4
    console.log('u< 5 ?', u, u < 5)
    ;async () => {
      while (u < 5) {
        console.log('starting u +...')
        await wait(800)
        console.log(u)
        u++
      }
    }
    t++
  }
}
n()
Raphaël Balet
  • 6,334
  • 6
  • 41
  • 78
  • OK I understand, but now can I make my first loop wait for completing the inner 2 while loops, I mean outer while loop will wait for each iteration until 2 inner while loops are not finished – Ayondip Jana May 09 '21 at 08:59
  • It's an other question that already have [answers](https://stackoverflow.com/a/60526968/11135174), please do accept the answer or extend your question if it does not satisfy your expectation. – Raphaël Balet May 09 '21 at 19:47
  • I did provide an example though, but still, the logic with the `t` variable does not make any sense. What are you trying to archive ? – Raphaël Balet May 09 '21 at 19:49