当我在浏览器中加载它时,它将显示页面完全加载时的时间,但不会每秒更新一次。我该怎么做?
var h = date.getHours(); if(h<10) h = "0"+h;
var m = date.getMinutes(); if(m<10) m = "0"+m;
var s = date.getSeconds(); if(s<10) s = "0"+s;
document.write(h + " : " + m + " : " + s);
答案 0 :(得分:7)
使用setInterval
:
setInterval(clock, 1000);
function clock() {
var date = new Date();
var h = date.getHours(); if(h<10) h = "0"+h;
var m = date.getMinutes(); if(m<10) m = "0"+m;
var s = date.getSeconds(); if(s<10) s = "0"+s;
document.write(h + " : " + m + " : " + s);
}
虽然您可能希望每秒向页面更新HTML
元素而不是document.write
。
答案 1 :(得分:0)
将其包裹在一个函数中并让它自己调用:
everysecond=1000; // milliseconds
function showCurrentTime(){
/*do your timing stuff here */
if(someConditionIsntMet) setTimeout(showCurrentTime, everysecond)
}