Mini Javascript Hackathon – Tix Clock

July 31, 2013   |   Reading time: ~3 mins

I’ve spent a lot of time recently writing C++, Python and Shell Script. These languages are great, but I fancied taking a break from them to go back to my old stomping ground. Earlier today I remembered about the existence of a cool little, almost completely useless, piece of geek tech known as the Tix clock. The premise of it is simple, it’s LEDs arranged in patterns that allow you to tell time. The way it’s worked out is that the lit LEDs in each segment add up to give you a part of the time. The first segment of three is the tens of hours, the second segment of 9 LEDs is the hours, the 3rd segment of 6 LEDs is the tens of minutes and the 4th segment of 9 LEDs is the minutes. So, for example if the lit LEDs on the clock were  1, 4, 3 and 6, it’d be 2:36 in the afternoon. If you’re still confused, then there’s plenty other places online who explain it much better than I do. I set myself a challenge to replicate the basic functionality of the Tix clock in an evening. I succeeded!

Behold, my replica of a Tix clock, built entirely in Javascript, HTML and a little CSS. This was completed in a about 2 hours, including the graphical tweaks to make it look slightly nicer. You can take a look at it in action right over here. There are probably much more elegant ways of doing it, but here’s how I made it.

First, we setup a 4 long array and populate each item in the array with another array that is equivalent in length to the number of blocks that will be representing that segment of the clock. We’re going to initialise the array to false. Next we’ll choose which blocks we’re going to be active by choosing random integers between 0 and the length of each array. If the index is already true, we’re going to skip this iteration and keep on looping. If it’s false we’re going to set it to true and increment the number of populated blocks by one. We’re going to do this until all the necessary blocks have been populated at pseudo randomly selected indices within the arrays. In this case we don’t really care about the quality or the spread of random numbers, it’s just computationally more efficient if we don’t get numbers which round down to the same value over and over again, as we’re basically blindly firing numbers at the algorithm and hope they stick.

Now we just render the clock to the document by removing all the contents of the container element and add the blocks, column by column, segment by segment. That’s all there is to it. There’s probably a much better way to do the rendering too, but for two hours  of chilled out work I don’t reckon it’s too bad.

Thanks for Reading.


You Might Also Like...

Leave a Reply

Your email address will not be published.


Sorry, there are currently no comments for this artcle. Why not start a conversation?