Coding a Clock — Programming Challenge for Beginners

Kamal Rathnayake
2 min readAug 23, 2021

When you know how to do something in pure HTML, CSS, and JS, without using the libraries others wrote, You really know how to do it. Also, this way of programming exercises the programming muscle of beginners really well.

Today, we’re going to see how you can program a clock with pure HTML, CSS, and JS without any libraries.

The HTML stuff

We are going to use SVG for drawing the clock. First, let’s learn how to draw a circle and few lines, bring them all together with some styling, and draw it.

The CSS stuff

Not much CSS is used here. Just to color the background. :)

28 Lines of JavaScript

Finally, let’s do the coding. First of all, we need a way to update the positions of the hands of the clock. This simple function will do it.

Now that we need to update the positions of these hands in a circular way we need to know about the concept of a unit circle.

Taken from onlinemathlearning.com

It is a very simple thing, based on the angle we can find the x and y positions.

For programmers, the unit circle would look something like this,

Given the angle and the radius, we can get the positions of the cartesian coordinates plane. Now let’s see the insides of this function named unitCircle.

Let’s write the fun stuff.

Finally, Seeing it ticking

Open the HTML in your browser and see your work.

And, You can find the code I wrote here. Cheers!

--

--

Kamal Rathnayake

Lead Software Engineer with 6 years of experience in the industry. Writing for fun!