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?
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.