快速(低占用空间)javascript时钟

时间:2011-02-28 16:05:43

标签: javascript optimization memory time

我正在尝试基于javascript创建一个实时时钟。

重要的是它保持较低的内存占用,同时保持准确。

这是我的代码:

<div id="time">...</div>

<script type="text/javascript">

    // I'm actually using a better name for such a global variable.
    // Here I'm presuming a lookup in a global variable is faster than to a local one
    var weekdays={"0":"Sun","1":"Mon","2":"Tue","3":"Wed","4":"Thur","5":"Fri","6":"Sat"};

    function refTime(){
      // get current time stamp
      var date=new Date();
      // add an hour so we get UTC+1
      date.setUTCHours(date.getUTCHours()+1) // UTC+1
      // store time components separately
      var day=date.getUTCDay(),
          hrs=date.getUTCHours(),
          min=date.getUTCMinutes(),
          sec=date.getUTCSeconds(),
          mer=false;
      // find meridiem and reduce 24h to 12h
      hrs=(mer=hrs<12) ? hrs : hrs-12;
      // generate the markup
      document.getElementById('time').innerHTML
        =weekdays[day]+'<br/>'+day+'<br/>'
        +(hrs<10?'0':'')+hrs+':'+(min<10?'0':'')+min+':'
        +(sec<10?'0':'')+sec+' '+(mer ? 'am' : 'pm');
    } // end format is: "Tue<br/>19<br/>11:43:25 am"
    setInterval(refTime,1000);

</script>

可以进一步优化吗?

备注:https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date

1 个答案:

答案 0 :(得分:0)

为什么不使用Date toYYYString()方法和String.split()之一来获取相应的字段。

UTC + 1有什么特别之处?如果用户在北美或亚洲,他们仍然需要UTC + 1?

您可以检测浏览器并处理几种不同的日期格式。不同的更明显的Date.toYYYString()方法结果:http://home.clara.net/shotover/datetest.htm