Making a live clock in javascript

Solution 1:

Add a span element and update its text content.

var span = document.getElementById('span');

function time() {
  var d = new Date();
  var s = d.getSeconds();
  var m = d.getMinutes();
  var h = d.getHours();
  span.textContent = 
    ("0" + h).substr(-2) + ":" + ("0" + m).substr(-2) + ":" + ("0" + s).substr(-2);
}

setInterval(time, 1000);
<span id="span"></span>

Answer updated [2021] https://stackoverflow.com/a/67149791/7942242

Solution 2:

You can also use toLocaleTimeString() on Date() to just get your display date instead of creating through so many variables.

window.onload = displayClock();
function displayClock(){
  var display = new Date().toLocaleTimeString();
  document.body.innerHTML = display;
  setTimeout(displayClock, 1000); 
}

Solution 3:

Here's my answer, hope it may help.

<html>

<body>
  <script type="text/javascript" charset="utf-8">
    let a;
    let time;
    setInterval(() => {
      a = new Date();
      time = a.getHours() + ':' + a.getMinutes() + ':' + a.getSeconds();
      document.getElementById('time').innerHTML = time;
    }, 1000);
  </script>
  <span id="time"></span>
</body>

</html>

I have used the setInterval arrow function and declared the variables a, time outside so as to avoid repeated allocation, where the span id(time) runs for a specified interval(here it is 1000) and document.getElementById("time") call gets you the element by the specified ID and also it's setting the innerHTML of that element to the value of time.

Solution 4:

Please follow this link https://codepen.io/uniqname/pen/eIApt you will get your desire clock or try this code

<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
}
</script>
</head>

<body onload="startTime()">

<div id="txt"></div>

</body>
</html>