我試過使用 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 次。”,但當我在確認()中按“確定”時,它不會重復;對話框。
我也試過這個:
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]);
最后,控制臺列印“此回圈已運行 1 次。” 并且 nOfTimesTheLoopRuns 的值是 1。我怎樣才能讓它在每次用戶在確認()中按下“確定”時保持運行;對話框?
uj5u.com熱心網友回復:
您可以將每次用戶確認時要執行的代碼放入一個函式中,然后rep在setTimeout回呼中檢查是否為真,如果是,則再次呼叫該函式:
let nOfTimesTheLoopRuns = 0;
function check() {
nOfTimesTheLoopRuns ;
console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
setTimeout(() => {
if (confirm("Repeat?")) {
check()
}
}, 2000)
}
check()
uj5u.com熱心網友回復:
如果 answer 為真,您可以使用呼叫自身的函式。
let nOfTimesTheLoopRuns = 0;
function test() {
if (confirm("Repeat") === true) {
nOfTimesTheLoopRuns ;
console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
setTimeout(() => test(), 2000);
}
}
test();
uj5u.com熱心網友回復:
這是因為 setTimeout 會在回圈完成后運行,這就是 javascript 處理異步函式的方式。通過閱讀事件回圈的概念,您可以更好地理解這一點
您可以做的是將所有代碼放在一個間隔中,并在用戶選擇“取消”時將其清除。
var nOfTimesTheLoopRuns = 0;
var myInterval = setInterval(function(){
nOfTimesTheLoopRuns ;
console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
if(!confirm("Repeat?")){
clearInterval(myInterval);
}
}, 3000);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343083.html
