Nancy Nancy - 6 months ago 19
HTML Question

Dynamically update time without refreshing the page

<html>
<head>
<script>
function updateClock() {
var time = now.getHours() + ':' + now.getMinutes(),
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
</script>
</head>
<body onload="updateClock()">
<p id="current"> </p>
</body>
</html>


Above is the code for dynamically update real time, it is not showing any thing on the browser. Would really appreciate help

Thank you.

Answer

Show time using Js :

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('current').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;
}
<body onload="startTime()">
  <p id="current">Time loading..</p>
</body>

OR

Your code edited:

function updateClock() {
  var now = new Date();
  var time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
  document.getElementById('current').innerHTML = time;
  setTimeout(updateClock, 1000);
}
<body onload="updateClock()">
  <p id="current"></p>
</body>

You were missing var now = new Date(); and also now.getSeconds();.

Comments