简体   繁体   中英

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.

There are some errors in updateClock:

function updateClock() {
  var now = new Date()
  var time = now.getHours() + ':' + now.getMinutes();
  document.getElementById('current').innerHTML = time;
  setTimeout(updateClock, 1000);
}

now must be a Date object.

  1. now needed to be a date object
  2. You had a comma instead of a semicolon after now.getMinutes(),

I recommend using
* padding
* setInterval
* window.onload instead of body onload

I added seconds to show it updates. If you only need hours and minutes, change the interval time to 10000 or so.

 function pad(num) { return String("0"+num).slice(-2); } function updateClock() { var now = new Date(); var time = pad(now.getHours()) + ':' + pad(now.getMinutes()) + ":" + pad(now.getSeconds()); document.getElementById('current').innerHTML = time; } window.onload = function() { setInterval(updateClock, 500); // use a shorter interval for better update } 
 <p id="current"></p> 

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(); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM