0

This HTML/Javascript code should output 1 to a paragraph, wait 5000 milliseconds then output 2, yet it waits for 5000 milliseconds and then outputs 12, why?

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <p id = "TotalOutputOut">
        </p>
        <script src = "Console.js">
        </script>
    </body>
</html>


function sleep(A){
    var FirstTime = new Date();
    var SecondTime = new Date();
    while (FirstTime.getTime() > (SecondTime.getTime() - A)){
        SecondTime = new Date();
    }
}
function print(A){
    TotalOutput = (TotalOutput + A);
    TotalOutputOut.innerHTML = TotalOutput; 
}
print("1");
sleep(5000);
print("2");
Community
  • 1
  • 1
  • 2
    Your `sleep` function blocks the browser, preventing it from rendering. While you can fix it by calling `sleep` and `print('2')` after a `setTimeout`, it would be much better to remove the `sleep` function entirely and calculate the timeout needed, then pass to `setTimeout` – CertainPerformance Mar 24 '20 at 08:28
  • `TotalOutput = (TotalOutput + A)` you made it in a way to concatenate the new value and the existing one. – MedAl Mar 24 '20 at 08:29

0 Answers0