我试过使用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次(s).",但是当我按下"Ok"时,它没有重复。在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 run 1 time(s)"。noftimestheeloopruns的值为1。我怎样才能使它在每次用户按下"ok"时都保持运行?在confirm()中;对话框?
您可以将每次用户确认时要执行的代码放入函数中,然后检查rep
在setTimeout
回调中是否为真,如果为真,则再次调用该函数:
let nOfTimesTheLoopRuns = 0;
function check() {
nOfTimesTheLoopRuns++;
console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
setTimeout(() => {
if (confirm("Repeat?")) {
check()
}
}, 2000)
}
check()
你可以使用一个函数,当答案为true时调用自己。
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处理异步函数的方式。您可以通过阅读事件循环
的概念来更好地理解这一点你能做的就是把你所有的代码放在一个间隔中,当用户选择'cancel'时清除它。
var nOfTimesTheLoopRuns = 0;
var myInterval = setInterval(function(){
nOfTimesTheLoopRuns++;
console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
if(!confirm("Repeat?")){
clearInterval(myInterval);
}
}, 3000);