I wanted to make a website. rough principle: The user can input time and rounds using the prompt() function. A loop that prints a text runs so often how the user entered it and between every print I want the loop to pause for the time, the user entered before.
I looked up lots of posts but there is nothing useful.
In the script, I used a sleep function which waits so long until the input time is equal to the current time, almost like the setTimeout() function but both don't work for me since it doesn't pause the whole script entirely. The script sleeps the time entered by user multiplied by the number of rounds and then it prints all the texts at the same time.
I want a function that can actually pause the loop and after the entered time it continues.
Sorry for bad English, need help
var textPara = document.getElementById("para");
var rounds = prompt("How often");
var count = 1;
do {
textPara.textContent += "Round " + count;
count++;
sleep(5000);
} while (count <= rounds)
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
<p id="para"></p>
IS this what you're wanting?
var textPara = document.getElementById("para");
var rounds = 5; // prompt("How often");
var count = 1;
var interval = 500;
function update(){
textPara.textContent += "Round " + count;
count++;
if (count <= rounds){setTimeout(update,interval)}
}
update();
<div id="para"></div>
In your original code, the event loop is blocked in the while loop and immediately moves on to the ensuing code, which triggers another sleep... and so the browser screen only updates once all the sleeping is over (the textContent value has updated multiple times in JS, but the browser doesn't show this).
In this example, the update function puts a new (recursive) call to itself in the future, but the event loop and browser are free to do updates in the interim, so we see the updates.
setTimeout can be useful this way even with an interval of zero to allow screen updates etc.