0

I just wanted to make a simple clock that tells you the time and not date. The problem with the code below though is that it shows the exact time of when the .html file is opened.

<body onload="showTime()">
<p id="time"</p>
<script>
var seconds;
var minutes;
var hours;
var time;

function showTime() {
    seconds = getSeconds();
    minutes = getMinutes();
    hours = getHours();
    document.getElementById("demo").innerHTML =
    hours +":"+ minutes +":"+ seconds; 
}

Is there anyway I could allow it to update automatically every second? Thanks.

2 Answers2

0

Try running the function every second using the setInterval() method. See this topic Run JavaScript function at regular time interval -not sure it is the best approach but it might work...

Community
  • 1
  • 1
samzmann
  • 2,286
  • 3
  • 20
  • 47
0

You need setInterval and a proper date object, but you do not want to execute that in a body tag.

<!DOCTYPE html>
<html>
  <head>
    <title>Clock</title>
    <script>
      window.onload=function() {
        setInterval(showTime,500); // run every 500ms
      }
      function pad(num) {
        return ("0"+num).slice(-2); // pad the number with leading 0
      } 
      function showTime() {
        var d    = new Date(), // now
         seconds = d.getSeconds();
         minutes = d.getMinutes();
         hours   = d.getHours();
         document.getElementById("demo").innerHTML = pad(hours) +":"+ pad(minutes) +":"+ pad(seconds); 
      } 
      </script>    
    </head>
    <body>
      <p id="demo"></p>
   </body>
</html>
mplungjan
  • 169,008
  • 28
  • 173
  • 236