While I was looking for an good example of an analog clock implemented only using Javascript I found this interesting clock written by Emanuele Feronato, using a very robust Javascript library called Raphaël
I was playing with it for a while and then I wanted to have multiple clocks with different times on those, maybe according to different timezones but that’s not the case here.
So what I did was create separate clock objects and set different times. It worked but the problem comes when the script hits the setInterval() function, it didn’t really work the clocks’ hands are not rotating.
I’m not so good at Javascript built-in functions and I couldn’t find a solution to prevent this issue, any way I’m posting my code here.
function createClocks(){
/* for the time being assume these Date objects are unique */
var diffDate_01 = new Date();
var diffDate_02 = new Date();
/* create separate clock Objects */
var clok_01 = new clock(diffDate_01);
var clok_01 = new clock(diffDate_02);
/* calling update_clock function wrapped within setInterval to make the clock's hand rotatable */
setInterval("clok_01.update_clock(diffDate_01)", 1000);
setInterval("clok_01.update_clock(diffDate_02)", 1000);
}
function clock(diffDate){
/* this is the place where the base implementation of the clock stands I removed the setInterval("update_clock()",1000); because I want to call it from outside as per Object separately */
function update_clock(diffDate){
var now = diffDate;
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
hour_hand.rotate(30*hours+(minutes/2.5), 100, 100);
minute_hand.rotate(6*minutes, 100, 100);
second_hand.rotate(6*seconds, 100, 100);
}
}
For the HTML part I’m creating dynamic clock <div> tags and append all those to one a <div> tag exists on the body of the HTML document.
Thanks.
Please, please don’t use strings with
setInterval()ever. That causes scope problems and potentially other problems.When you use a string, that string is evaluated with
eval()at the global scope. As such it has NO access to any of your local variables. There were also a number of other problems, including the fact that you didn’t make update_clock a method of the clock object.Here’s a working, rewritten and cleaned up version of the code that is much more object oriented and supports several new methods: http://jsfiddle.net/jfriend00/wKVC7/
And, here’s the code: