如何让时间功能更新?

时间:2013-05-04 11:51:58

标签: javascript function time setinterval

当我在浏览器中加载它时,它将显示页面完全加载时的时间,但不会每秒更新一次。我该怎么做?

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);

2 个答案:

答案 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

http://jsfiddle.net/bQNwJ/

答案 1 :(得分:0)

将其包裹在一个函数中并让它自己调用:

everysecond=1000; // milliseconds
function showCurrentTime(){
    /*do your timing stuff here */
    if(someConditionIsntMet) setTimeout(showCurrentTime, everysecond)
}