我怎样才能循环一些代码,以便每次 confirm() returns true 时它都重复?

How can I loop some code so that it repeats every time confirm() returns true?

我试过使用 do-while 循环,但它似乎无法正常工作:

let rep; //this variable tells the loop whether to run or not
let nOfTimesTheLoopRuns = 0;

do {
    nOfTimesTheLoopRuns++;
    console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);

    setTimeout( () => {
        rep = confirm("Repeat?");
    }, 2000); //a delay is set so that the answer can be printed on the console before the code runs again
} while (rep);

控制台打印:“此循环有 运行 1 次。”,但当我在 confirm() 中按“确定”时,它没有按应有的方式重复;对话框。

我也试过这个:

let rep = []; //this variable tells the loop whether to run or not
let nOfTimesTheLoopRuns = 0;

do {
    rep.pop();

    nOfTimesTheLoopRuns++;
    console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);

    setTimeout( () => {
        rep.push(confirm("Repeat?"));
    }, 2000); //a delay is set so that the answer can be printed on the console before the code runs again
} while (rep[0]);

最后,控制台打印“This loop has 运行 1 time(s).” nOfTimesTheLoopRuns 的值为 1。我怎样才能让它保持 运行ning 每次用户在 confirm() 中按下“Ok”;对话框?

你可以将每次用户确认时要执行的代码放入一个函数中,然后在setTimeout回调中检查rep是否为真,如果是则再次调用该函数:

let nOfTimesTheLoopRuns = 0;

function check() {
  nOfTimesTheLoopRuns++;
  console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
  setTimeout(() => {
    if (confirm("Repeat?")) {
      check()
    }
  }, 2000)
}


check()

您可以使用一个在答案为真时调用自身的函数。

let nOfTimesTheLoopRuns = 0;
function test() {
  if (confirm("Repeat") === true) {
    nOfTimesTheLoopRuns++;
    console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
    setTimeout(() => test(), 2000);
  }
}
test();

这是因为setTimeout会在循环完成后运行,这就是javascript处理异步函数的方式。您可以通过阅读 Event loop

的概念来更好地理解这一点

您可以做的是将所有代码放在一个区间内,并在用户选择 'cancel' 时清除它。

var nOfTimesTheLoopRuns = 0;
var myInterval = setInterval(function(){
    nOfTimesTheLoopRuns++;
    console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
    if(!confirm("Repeat?")){
       clearInterval(myInterval);
    }
}, 3000);