Clock

markuswedler

Markus Wedler

Posted on August 9, 2022

Clock

The Website: Link

So I made a clock. At first I was trying to code it via React but couldn't find the way to create infinite loop that would start after page initial render - React was spamming error messages in the console if using useEffect and it wasn't even allowing page to load if using recursive function.

And I used recursive function in common HTML project. Luckily it worked and it wasn't too difficult do code a clock hands. In few words, recursive function was just checking every 1/10s current system time and setting angle for the hands using simple formula:

angle = 360 / marks_num * time_value
Enter fullscreen mode Exit fullscreen mode

where marks_num is the number of current hand's marks (for hours it's 12, for minutes and seconds it's 60)

We also have to make out hands to move smoothly (optional for seconds) so we also add the current state of lower time dimensions.
For hours it's:

minutes / 60 + seconds / 3600
Enter fullscreen mode Exit fullscreen mode

For minutes it's:

seconds / 60 + milliseconds / 60000
Enter fullscreen mode Exit fullscreen mode

So as the result it looks like this:

document.querySelector('.h-hand').style.transform = "rotate("+30*(now.getHours()+now.getMinutes()/60+now.getSeconds()/3600)+"deg)"
document.querySelector('.m-hand').style.transform = "rotate("+6*(now.getMinutes()+now.getSeconds()/60+now.getMilliseconds()/60000)+"deg)"
document.querySelector('.s-hand').style.transform = "rotate("+6*(now.getSeconds())+"deg)"
Enter fullscreen mode Exit fullscreen mode

The Full Code

GitHub: Link

💖 💪 🙅 🚩
markuswedler
Markus Wedler

Posted on August 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related