New to Owl Order? Click here for 2009's best posts! 00:00:00

Sunday, 23 May 2010

Web Gadgets: JavaScript Clock

See the little clock up there? Right above the big red seal? That's a little clock I wrote. Most blogs utilise Flash to implement clocks, but Flash is slow, resource hungry and doesn't work on mobile devices, including iPhones, iPods and iPads.

The clock I wrote, however, is pure JavaScript. Most browsers today have fast JavaScript engines, including mobile browsers, so it's guaranteed to run almost everywhere. It's actually very simple, a few lines of code do the trick.
<span id="clock"></span>
<script type="text/javascript">
update();
function update()
{
var now=new Date();
document.getElementById("clock").innerHTML=
twodigit(now.getHours())
+":"+twodigit(now.getMinutes())
+"<sub>:"+twodigit(now.getSeconds())+"</sub>";
setTimeout("update()",1000-(now.valueOf()%1000));
}
function twodigit(ip)
{
if (ip<10)
return new String("0"+ip);
else
return ip;
}</script>
A little example. This example is hosted on a free webhost, so don't be surprised if it doesn't load. The one on top of this page always loads, though.


I sincerely urge users of Flash-based clock-gadgets to switch to a JavaScript-based one. Feel free to copy the code above and modify it, if you know basic HTML/JavaScript. Note that Blogspot blocks JavaScript codes unless they're in proper HTML/JavaScript gadgets.

PS: See here for an analogue JavaScript clock.

2 comments:

  1. that's all cool & great js clock, thank you very much for sharing.

    Can you give me favor by sharing this clock on my JavaScript library?


    Awaiting your response. Thank

    ReplyDelete
  2. i'm not sure how to fill up the form. i filled it up and submitted it anyway. either way i don't think this simple gadget really deserves a spot in your library, it's barely a few lines of code, anyone with simple knowledge of JS date object can cook it up within minutes.

    thanks for the offer though.

    ReplyDelete

Note: only a member of this blog may post a comment.