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"));
})();
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"));
})();
You could use window.setTimeout
or window.setInterval
. You have to update the time every seconds (1000 ms).
(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>
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>
You should use setInterval
. This will call your function every 1000
ms
function time() {
console.log(new Date().toString("hh:mm:ss tt"));
};
setInterval(time, 1000);
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.