Solved the second challenge from Wes Bos “JavaScript30”.
I followed along with the video until he said stop and then continued to solve the rest, it was maybe a bit too easy after he showed the second-hand of the clock.
However, after finishing the clock I continued to refactor it and made it much more optimized than the original solution.
I choose to lift out the actual rotation of each and, setting the date only 1 time and then just add 1 second to the date for each interval instead of creating new date objects every second…
At last I fixed the minute bug by removing a class “trans” that adds the transition and adding it back in if it doesn’t exist.
Full solution: https://github.com/alexanderanter/JavaScript30/tree/solutions/02-JSandCSSClock
Edited CSS
.hand { width:50%; height:6px; background:black; position: absolute; top:50%; transform-origin:100%; -webkit-transform: rotate(90deg); transform: rotate(90deg); transition-timing-function: cubic-bezier(1, 0.01, 0.24, 1.28) } .trans { transition: all 0.3s; }
JS
const secondHand = document.querySelector('.second-hand'); const hourHand = document.querySelector('.hour-hand'); const minHand = document.querySelector('.min-hand'); var now = new Date(); //Make the clock tick by adding 1 second and set each clock hand to its current position function rotateClock(){ now.setSeconds(now.getSeconds() + 1); setHand(secondHand, now.getSeconds(), 60); setHand(minHand, now.getMinutes(), 60); setHand(hourHand, now.getHours(), 24); } //Accepts the clockhand, timing and the parts the clock-hand is divided by for full circle function setHand(hand, timing, dividedBy ){ const degrees = ((timing / dividedBy) * 360) + 90; //avoid transition bug when it changes minute if(hand == secondHand && degrees == 90){ hand.classList.remove('trans'); }else if(hand == secondHand && hand.classList.contains('trans') !== true) { hand.classList.add('trans'); } hand.style.transform = 'rotate(' + degrees + 'deg)'; } //Rotate the clock to the current time setInterval(rotateClock, 1000);