【问题标题】:How to make time function update itself?如何让时间函数自动更新?
【发布时间】:2013-04-28 17:54:51
【问题描述】:

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

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​​​​​​​​​​​​​​​​
  • 试试这个examplew3schools
  • @LuigiSiri 不要使用 w3schools 永远 &gt;:(
  • @LuigiSiri: w3fools.com

标签: javascript function time setinterval


【解决方案1】:

使用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/

【讨论】:

    【解决方案2】:

    把它封装在一个函数中,让它自己调用:

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

    【讨论】:

    • 非常糟糕。设置间隔更适合这个
    • 没有。 SetIntervall 也不是更好。它正在进行中。使用自调用功能,您可以在给定条件下中止。没有简单的方法来中止 setInterval
    • @Lilith2k3 ...是的。什么样的逻辑让你觉得这样更好?
    • @Doorknob:就像他说的,它更灵活。您可以从 setTimeout 轻松构建 setInterval,但反之则不行。
    • setInterval 对于这个目的更糟,因为它不依赖于运行函数所需的时间。如果运行该功能需要很长时间,您不想同时更新。见stackoverflow.com/a/731625/309483PERIOOOOOOOOOOOOD
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2010-11-23
    相关资源
    最近更新 更多