Search code examples
javascriptreal-time-clock

How should I use setTimeout in this Javascript real-time-clock?


I was trying to do a real-time-clock but I'm having a problem, the setTimeout isn't working in fact the clock doesn't update itself. May I have your help please?

This is the code that I wrote:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>
  <p id="p"></p>
  <script>
    var currentDate = new Date();

    function startClock() {

      time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();

      document.getElementById("p").innerHTML = time;

      setTimeout(startClock, 1000);
    }

    startClock();
  </script>
</body>

</html>


Solution

  • Actually, the setTimeout is working fine, however you instantiate currentDate outside of the function, so it never updates.

    This is because the time is only captured when the date is instantiated-- it doesn't update itself. That means if you only instantiate it once, it will only ever hold the time from when it was instantiated.

    Try this:

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <title></title>
    </head>
    
    <body>
      <p id="p"></p>
      <script>
        
    
        function startClock() {
          var currentDate = new Date();
      
          time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
    
    
          document.getElementById("p").innerHTML = time;
    
          setTimeout(startClock, 1000);
        }
    
        startClock();
      </script>
    </body>
    
    </html>