Clock

Page section: playground

This uses JS to update the time every second. The number of hours, minutes and seconds are converted into degrees and used to set the inline-style value of transform-rotate() for each of the hands.

00
00
00

The clock needs to get the CSS transition working so that the hand does not reverse a full turn and instead just keep going through 12 o’clock. Also could make it so the hour hand advances through 15 degrees every 30 mins.

View contents of: /static/js/clock.js
// For testing use blank.js - still has this code in it.

// currently used by clock.md

const hands = document.querySelectorAll('.hand');
const secondHand = document.querySelector('.second-hand');
const minuteHand = document.querySelector('.minute-hand');
const hourHand = document.querySelector('.hour-hand');

const digitalHours = document.querySelector('#d-hours');
const digitalMinutes = document.querySelector('#d-minutes');
const digitalSeconds = document.querySelector('#d-seconds');

// The main function that does everything
function setTime() {
  const now = new Date();
  const seconds = now.getSeconds();
  //   seconds = ('0' + seconds).slice(-2);
  seconds.toString().padStart(2, '0'); // don't work
  const minutes = now.getMinutes();
  const hours = now.getHours();
  const secondsDegrees = seconds * 6 + 90; // 6 * 60sec = 360deg
  const minutesDegrees = minutes * 6 + 90;

  const hoursDegrees = (hours / 12) * 360 + 90;
  // const hoursDegrees = () => {
  //   if (minutes < 30) {
  //     ((hours / 12) * 360 )- 30;
  //   } else {
  //     (hours / 12) * 360 + 105;
  //   }
  // };

  // Attempt to stop second hand rewinding to zero
  // if (seconds == 0) {
  //   hands.forEach(hand, () => {
  //     hand.style.transitionDuration = '0';
  //   })

  // }

  secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
  minuteHand.style.transform = `rotate(${minutesDegrees}deg)`;
  hourHand.style.transform = `rotate(${hoursDegrees}deg)`; // has to move 6 deg every 12 mins

  // for the digital clock section

  // Add a zero before single digits
  function nn(n) {
    return (n < 10 ? '0' : '') + n;
  }

  digitalHours.textContent = nn(hours) + ':';
  digitalMinutes.textContent = nn(minutes) + ':';
  digitalSeconds.textContent = nn(seconds);

//   console.log(hours + ' degrees: ' + hoursDegrees);
}

// run the function once every second
setInterval(setTime, 1000);