I've tried using do-while loops but it doesn't seem to be working properly:
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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The console prints: "This loop has run 1 time(s).", but it doesn't repeat as it should when I press "Ok" in the confirm(); dialog box.
I've also tried this:
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]);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
In the end, the console prints "This loop has run 1 time(s)." And the value of nOfTimesTheLoopRuns is 1. How can I make it so that it keeps running every time the user presses "Ok" in the confirm(); dialog box?
CodePudding user response:
You can do put the code you want to execute each time the user confirms into a function, then check whether rep
is true in the setTimeout
callback and call the function again if so:
let nOfTimesTheLoopRuns = 0;
function check() {
nOfTimesTheLoopRuns ;
console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
setTimeout(() => {
if (confirm("Repeat?")) {
check()
}
}, 2000)
}
check()
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use a function that calls itself if answer is true.
let nOfTimesTheLoopRuns = 0;
function test() {
if (confirm("Repeat") === true) {
nOfTimesTheLoopRuns ;
console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
setTimeout(() => test(), 2000);
}
}
test();
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
This is because the setTimeout would run after the completion of the loop, that's how the javascript handles asynchronous functions. You can better understand this by reading concept of Event loop
What you can do is to put all your code in an interval and clear it when user selects 'cancel'.
var nOfTimesTheLoopRuns = 0;
var myInterval = setInterval(function(){
nOfTimesTheLoopRuns ;
console.log(`This loop has run ${nOfTimesTheLoopRuns} time(s).`);
if(!confirm("Repeat?")){
clearInterval(myInterval);
}
}, 3000);