我正在尝试创建一个基于 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
最佳答案
为什么不使用 Date toYYYString() 方法和 String.split() 之一来获取适当的字段。
UTC+1 有什么特别之处?如果用户位于北美或亚洲,他们仍然需要 UTC+1?
您可以检测浏览器并处理几种不同的日期格式。不同的浏览器 Date.toYYYString() 方法结果:http://home.clara.net/shotover/datetest.htm
关于javascript - 快速(占用空间少)的 JavaScript 时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5144385/