Challenge 6: Enhanced Clock 🕰️

Learnings
Understanding Clock Rotation Using CSS Variables
We dynamically create 12-hour markers on the clock face.
Each marker is rotated by 30° (
360° / 12
).We use the CSS variable
--rotation
to rotate each number accordingly.
Example:
for (let i = 1; i <= 12; i++) {
const number = document.createElement('div');
number.className = 'number';
number.style.setProperty('--rotation', `${i * 30}deg`);
number.innerHTML = `<span>${i}</span>`;
clockFace.appendChild(number);
}
- CSS applies rotation:
.number {
position: absolute;
transform: rotate(var(--rotation));
}
Digital Clock Display & Formatting
String(now.getHours()).padStart(2, '0')
ensures two-digit formatting.toLocaleDateString()
formats the date in a readable way.
Example:
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
digitalClock.textContent = `${hours}:${minutes}:${seconds}`;
Handling Clock Hands Movement Smoothly
Ratios convert time into degrees for smooth hand rotation.
setRotation(element, rotationAngle)
applies rotation via CSS.
Example:
const secondRatio = now.getSeconds() / 60;
const minutesRatio = (secondRatio + now.getMinutes()) / 60;
const hoursRatio = (minutesRatio + now.getHours()) / 12;
setRotation(secondHand, secondRatio * 360);
setRotation(minuteHand, minutesRatio * 360);
setRotation(hourHand, hoursRatio * 360);
Fixing the "Jumping" Effect at 360° to 0° Transition
The second hand was jumping back from
360° → 0°
.We remove
transition
temporarily when it resets.
Example:
function setRotation(element, rotation) {
if (element === secondHand && rotation === 0) {
element.style.transition = 'none';
} else {
element.style.transition = ''; // Reset to CSS default
}
element.style.transform = `translateX(-50%) rotate(${rotation}deg)`;
}
Using
setInterval
for Real-Time UpdatesThe clock updates every second (
1000ms
).The initial call to
updateClock()
ensures no delay on page load.
Example:
updateClock();
setInterval(updateClock, 1000);
Key Takeaways
✅ CSS transforms (rotate
) allow smooth analog clock behavior.
✅ padStart(2, '0') ensures a consistent digital clock format.
✅ CSS variables (--rotation
) make rotation calculations easy.
✅ Handling smooth transitions prevents unwanted jumps at 360°
.
This makes the Enhanced Clock precise, smooth, and visually appealing! ⏳🚀
Subscribe to my newsletter
Read articles from Virat Srivastava directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
