簡體   English   中英

為什么我的代碼在幾個循環后停止工作?

[英]Why does my code stop working after few 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) 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...

有人在我的代碼中看到錯誤嗎?

您的第一個while循環不會等待任何內容,而是會直接執行。

然后,你寫了

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

但是在第二個循環中, i將等於5 -> 它不再運行,對於u也是如此。

所以它只會運行一個,就像說你的第一個while有點沒用一樣。

如果答案對您沒有幫助,您可以提供更多信息,我會改進它。

回復下面的評論

我可以讓我的第一個循環等待完成內部 2 while 循環嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM