My code:
<!DOCTYPE html>
<html>
<body>
<button id="start" onClick="myFunction()">Start</button>
<div id="output"></div>
<script>
function myFunction() {
for(i=3; i>0; i--) {
console.log(i);
document.getElementById('output').innerHTML = i;
pause(5000);
}
}
function pause(milliseconds) {
var dt = new Date();
while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}
</script>
</body>
</html>
Numbers 3, 2 and 1 appear in console at intervals of 5 seconds, but in div appear number 1 (actually all numbers) after 15 seconds. Why console is not synchronized with display? Exist other method to stop rime between instructions?
The reason your function fails to work is, basically, that DOM changes arent processed and displayed until everything finishes running for a second. The easiest way to make it work would probably be a call to setTimeout
which waits a specific amount of time then calls the supplied function. For example you could use the following function to make your code work.
This function recursively calls itself via a setTimeout
call to make sure the DOM is udpated.
function myFunction(i) {
(function doStuff() {
console.log(i);
document.getElementById('output').innerHTML = i;
i -= 1;
if (i >= 0) {
setTimeout(doStuff, 5000);
}
}());
}
myFunction(3);
<div>
Counter: <span id="output">X</span>
</div>