In this lesson I create an analog clock that displays the users' current time.
To start the clock I run a function setDate() every second (setInterval(setDate, 1000)).
In setDate() - First get the current time. Using the current time also get the time in seconds, minutes and hours. Then calculate the degree of rotation for each hand, offset by +90 to ensure the rotation of the element starts north.
Finally, query the 'document' for each hand element and rotate each hand using the matching degree value. I do this by using es6 template strings to inject the variable into the elements' 'style' attribute (secondHand.style.transform = `rotate(${secondsDegrees}deg)`).
See the Pen
JavaScript30 - 2 - Clock by Corey Noble (@CoreyNoble)
on CodePen.