如何让我的时钟自动刷新,因为它只显示页面加载的时间?
(function time () {
document.write(new Date().toString("hh:mm:ss tt"));
})();
答案 0 :(得分:1)
您应该使用setInterval
。这将每隔1000
ms
function time() {
console.log(new Date().toString("hh:mm:ss tt"));
};
setInterval(time, 1000);
答案 1 :(得分:1)
您可以使用window.setTimeout
或window.setInterval
。您必须每秒更新一次时间( 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>
&#13;
function time () {
document.getElementById("time").innerHTML = new Date().toString("hh:mm:ss tt");
}
var timeInterval = setInterval(time, 1000); // recalls the function every 1000 ms
&#13;
<div id="time"></div>
&#13;
答案 2 :(得分:0)
这种方法需要在您的html模板中使用<div id="txt"></div>
:
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()">