-1

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>
Pier
  • 103
  • 1
  • 11

2 Answers2

3

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>
user184994
  • 17,791
  • 1
  • 46
  • 52
0

Use setTimeout is correct. But it is not best solution. Because it will consume memory exponentially when you call itself.

So, you can use setInterval instead of setTimeout:

<!DOCTYPE html>
<html>

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

<body>
  <p id="p"></p>
  <script>
    

    function startClock() {
      let currentDate = new Date();
  
      time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();


      document.getElementById("p").innerHTML = time;
    }
    setInterval(startClock, 1000);
  </script>
</body>

</html>
The Manh Nguyen
  • 406
  • 6
  • 19