I created a clock for my page using JavaScript - code below. Initially it created a new Date() object each time and then created vars to build the date and time format. This seemed an unnecessary overhead and I'm trying to get it to run quickly/efficiently - (I don't mean to 'run fast' ).
So I'm just creating the Date() object once and adding 3 seconds to it each time - of course, I'm only updating it every three seconds as well. Is there anything I should be aware of with this method? Will the clock suddenly be wrong at, say, the end of the month? It's hard for me to tell if there might be a problem
Code: Select all
Date.prototype.getMonthName = function() {
var mthName = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return mthName[this.getMonth()];
}
Date.prototype.getDayName = function() {
var dayName = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
return dayName[this.getDay()];
function GetToday(full) // returns a string with today's date
{ // if full is 'true', returns a fuller version of the date (incl. Thu, Jan)
( this.currDT ) ? this.currDT.setSeconds(this.currDT.getSeconds()+3) : this.currDT = new Date();
this.currDate = currDT.getDate();
this.currMonth = currDT.getMonth()+1;
this.currYr = currDT.getFullYear();
this.currHr = currDT.getHours();
this.currMin = currDT.getMinutes();
this.currTime = ( currHr < 10 ? "0" : "" ) + currHr + ':' + ( currMin < 10 ? "0" : "" ) + currMin;
currDate = ( currDate < 10 ? "0" : "" ) + currDate; // Pad with leading zeros, if required
currMonth = ( currMonth < 10 ? "0" : "" ) + currMonth;
if ( full )
return currDT.getDayName() + ' ' + currDate + ' ' + currDT.getMonthName() + ' ' + currYr + ' ' + currTime;
else
return currDate + '/' + currMonth + '/' + currYr + ' ' + currTime;
}
var UpdateClock = function () { $('myClock').firstChild.nodeValue = GetToday(true); }
window.setInterval(UpdateClock, 3000);