当我在浏览器中加载它时,它会显示页面完全加载的时间,但不会每秒更新一次。我该怎么做呢?
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);
当我在浏览器中加载它时,它会显示页面完全加载的时间,但不会每秒更新一次。我该怎么做呢?
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);
使用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
将其包装在一个函数中并让它调用自己:
everysecond=1000; // milliseconds
function showCurrentTime(){
/*do your timing stuff here */
if(someConditionIsntMet) setTimeout(showCurrentTime, everysecond)
}