1

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?

alexeevyci
  • 271
  • 1
  • 5
  • 16
  • 3
    [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout) (note by googling "Stop time for a few seconds in javascript", you'll find plenty of answers!) – Sterling Archer Dec 28 '15 at 20:53
  • 1
    You are essentially blocking the whole thing, even browser repaints. – MinusFour Dec 28 '15 at 20:53
  • 3
    Infinite blocking loops are *almost never* a valid way to pause execution. – David Dec 28 '15 at 20:56

1 Answers1

1

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>
Marie
  • 2,114
  • 1
  • 17
  • 31