1

How do I make my clock auto refresh, because it only shows the time the page was loaded?

(function time () {
    document.write(new Date().toString("hh:mm:ss tt"));
})();
Jason Aller
  • 3,541
  • 28
  • 38
  • 38

3 Answers3

2

You could use window.setTimeout or window.setInterval. You have to update the time every seconds (1000 ms).

setTimeout

(function time () {
 document.getElementById("time").innerHTML = new Date().toString("hh:mm:ss tt");
        var timeout = setTimeout(time, 1000); // recalls the function after 1000 ms
})();
<div id="time"></div>

setInterval

function time () {
 document.getElementById("time").innerHTML = new Date().toString("hh:mm:ss tt");
}
var timeInterval = setInterval(time, 1000); // recalls the function every 1000 ms
<div id="time"></div>
jak.b
  • 273
  • 4
  • 15
1

You should use setInterval. This will call your function every 1000ms

function time() {
  console.log(new Date().toString("hh:mm:ss tt"));
};

setInterval(time, 1000);
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
0

This approach requires, say, <div id="txt"></div> in your html template:

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

function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var ampm = h >= 12 ? 'PM' : 'AM';
h = h % 12;
h = h ? h : 12; // the hour '0' should be '12'
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s + " " + ampm;
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()">

See also How to format a javascript Date.
And here is the demo.

dhilt
  • 18,707
  • 8
  • 70
  • 85