0

I am making a clock in JavaScript and part of it is of course the while loop to constantly update the time. I have searched this error up and it says that running a while loop makes JavaScript unresponsive. I don't know how to substitute the while loop and why I can't seem to put one there. Help would be greatly appreciated. Here is the error and code.


var today = new Date();
var hours;
var minutes;
var seconds;
var percentage;
var time;
var clock = document.getElementById("clockHeading");
while (true){
    hours = today.getHours();
    hours = hours*3600;
    minutes = today.getMinutes();
    minutes = minutes*60;
    seconds = today.getSeconds();
    seconds = seconds+minutes+hours;
    percentage = seconds/48600;
    percentage = String(percentage);
    percentage = percentage+"%";
    time = document.createTextNode(percentage);
    clock.appendChild(time);
}
body{
    font-family: "Raleway";
}
#clockHeading{
    position: fixed;
    top: 50%;
    width: 100%;
    text-align: center;
    font-size: 200px;
}
<!DOCTYPE html>
<html>
    <head>
        <title>Percent Clock</title>
        <link href="style.css" rel="stylesheet">
        <link rel="preconnect" href="https://fonts.gstatic.com">
        <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@300&display=swap" rel="stylesheet">
    </head>
    <body>
        <h1 id="clockHeading"></h1>
        <script type="text/javascript" src="clock.js"></script>
    </body>
</html>

enter image description here

Sebastian Power
  • 85
  • 3
  • 10
  • Browser becomes unresponsive because JS runs on single thread and running an infinite loop will block the thread. As mentioned in this article https://stackoverflow.com/questions/38670964/the-page-became-unresponsive-when-the-while-loop-is-working You can use for example `setInterval()` – Aalexander Feb 17 '21 at 08:05

1 Answers1

2

while(true) will continuously run, blocking the main thread. If you need it to run continuously for a clock, you're better off using setInterval or a recursive setTimeout:

setInterval(() => {
  // Your code
}, 1000)

or:

function timer() {
  setTimeout(() => {
    // Your code

    timer()
  }, 1000)
}

timer()

See this post for the difference between them.


Example:

var clock = document.getElementById("clockHeading");

setInterval(() => {
  var today = new Date();
  var hours = today.getHours() * 3600;
  var minutes = today.getMinutes() * 60;
  var seconds = today.getSeconds() + minutes + hours;
  var percentage = String(seconds / 48600) + '%';

  clock.innerHTML = percentage;
}, 1000)
body {
  font-family: "Raleway";
}

#clockHeading {
  position: fixed;
  top: 50%;
  width: 100%;
  text-align: center;
  font-size: 20px;
}
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@300&display=swap" rel="stylesheet">

<h1 id="clockHeading"></h1>
Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49