I'm trying to create a live clock based on javascript.
The important part is that it keeps a low memory footprint, meanwhile staying accurate at the same time.
This is my code:
<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>
Can it be further optimized?
Notes: https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date
Why not use one of the Date toYYYString() methods and String.split() to get the appropriate fields.
What's so special about UTC+1? If the user is in North America or Asia, they'll still want UTC+1?
You could detect the browser and handle the couple of different date formats. Different broser Date.toYYYString() method results: http://home.clara.net/shotover/datetest.htm
精彩评论