Thought I'd do a little test, to test my skill set after being away from javascript for too long. Tried to be really cwleaver and create an object of a clock, sounds simple enough. I managed to create the clock etc with no trouble but after running the script after roughly 20 minutes, I noticed my clock was serval minutes behind! No idea what I've done.
This is only a little hobby project, I'm not gaining from this at all. Any criticisms accepted :)
function clock24(element){
this.date=new Date;
this.seconds=this.date.getSeconds();
this.minutes=this.date.getMinutes();
this.hours=this.date.getHours();
this.ele=element;
this.output={seconds:"00",minutes:"00",hours:"00"};
this.update();
var self=this;
this.ele.html(this.output['hours']+":"+this.output['minutes']+":"+this.output['seconds']);
this.increment=setInterval(function(){
self.seconds++;
if(self.seconds==60){
self.seconds=0;
self.minutes++;
}
if(self.minutes==60){
self.minutes=0;
self.hours++;
}
if(self.hours==24){
self.hours=0;
}
self.update();
self.ele.html(self.output['hours']+":"+self.output['minutes']+":"+self.output['seconds']);
},1000);
}
clock24.prototype={
constructor:clock24,
update:function(){
this.output['seconds']=(this.seconds<10)?"0"+this.seconds.toString():this.seconds.toString();
this.output['minutes']=(this.minutes<10)?"0"+this.minutes.toString():this.minutes.toString();
this.output['hours']=(self.hours<10)?"0"+this.hours.toString():this.hours.toString();
}
}
My guesses are, something in the script takes too long to compute but is minimally noticeable? Or the way I've structured my script?
Can't put my finger on it, but! I bet it's something really stupid and I apologise for my stupid question in advance XD
shennan :
I'd probably do it a bit like this:\n\n\r\n\r\nfunction clock24(el){\r\n\r\n var started, interval, seconds, minutes, hours;\r\n\r\n this.update = function(){\r\n\r\n var time = new Date(new Date().getTime() - started);\r\n \r\n seconds = time.getSeconds();\r\n minutes = time.getMinutes();\r\n hours = time.getHours();\r\n\r\n var pretty = hours + ':' + minutes + ':' + seconds;\r\n\r\n if(typeof jQuery !== 'undefined' && el instanceof jQuery)\r\n el.html( pretty );\r\n else\r\n el.innerHTML = pretty;\r\n \r\n return this;\r\n \r\n }\r\n \r\n this.start = function(){\r\n\r\n started = new Date().getTime();\r\n \r\n this.update();\r\n \r\n interval = setInterval(this.update, 1000);\r\n \r\n return this;\r\n \r\n }\r\n \r\n this.stop = function(){\r\n \r\n clearInterval(interval);\r\n \r\n return this;\r\n \r\n }\r\n\r\n return this;\r\n\r\n}\r\n\r\nvar clock = clock24(document.body).start();\r\nbody {\r\n \r\n font-family: Arial, Helvetica, sans-serif;\r\n font-size: 2em;\r\n\r\n}",
2015-01-30T17:52:51