JavaScript clock part 1: simple digital clock


Tagged , ,

Recently I need to put a set of JavaScript clocks for different timezones on a web page, while I was not allowed to use any JavaScript libraries or plugin (like jClock). The clock doesn’t need to have a fancy interface which a simple digital clock with HH:MM:SS would do, thus I decided to write a very simple clock object on my own.

To achieve my goals, the clock object should be able to:

Finally I came up with this little clock object script (and its minified version). Let’s say now I want to put 2 clocks on the page, one is for Hong Kong ( UTC + 8 ), one is for Melbourne ( UTC + 10 ) and the current UTC time is 1 Jul 2009 1:00pm, I can do something like:

var clock1 = new www.ui.Clock('container1');
var clock2 = new www.ui.Clock('container2');

clock1.init({ date:'July 1, 2009 13:00:00', utcOffset:8 });
clock2.init({ date:'July 1, 2009 13:00:00', utcOffset:10 });

clock1.start();
clock2.start();

You can find the working sample here and it works for the following browsers on Windows:

UPDATE: It seems Firefox 2 doesn’t like the setInterval() call and breaks the code (you will see what I mean by loading the sample in FF2). If you want to use the script and you need to support Firefox 2, just simply change the setInterval() call to setTimeout() (of course you will also need to call the setTimeout() in the update() method).

1 comment

RSS / trackback

respond

  1. www@www » JavaScript clock part 2: analog clock

    on July 3, 2009 at 9:40 am

    [...] » [...]