Search code examples
javascriptjquerynode.jsgithubweb

Working of Digital Analog Clock in Javascript


I am a beginner and I couldn't understand the working of a Digital analog it left me confused. I was given a clock.png and only the working of clock's hand was a bit complicating.

Javascript -

const deg = 6; // setting up the value
const hr = document.querySelector('#hr'); 
const mn = document.querySelector('#mn'); 
const sc = document.querySelector('#sc'); 

setInterval(() => {

    let day = new Date(); 
    let hrs = day.getHours() * 30; 
    let min = day.getMinutes() * deg; 
    let sec = day.getSeconds() * deg; 
    
    hr.style.transform = `rotateZ(${(hrs)+(min/12)}deg)`;
    mn.style.transform = `rotateZ(${min}deg)`;
    sc.style.transform = `rotateZ(${sec}deg)`;

})


I just want to know how the set interval Function.


Solution

  • As stated in the docs MDN - setInterval, setInterval has optional second parameter, called delay (defined in milliseconds, default value 0). In your case, internval function needs to be called every second, so you need to pass 1000 as delay parameter value.

    Below is complete working code, including example HTML/CSS.

    const deg = 6;
    const hr = document.querySelector('.hour-hand');
    const mn = document.querySelector('.minute-hand');
    const sc = document.querySelector('.second-hand');
    
    setInterval(() => {
        let day = new Date();
        let hrs = day.getHours() * 30;
        let min = day.getMinutes() * deg;
        let sec = day.getSeconds() * deg;
    
        // Rotating the hour, minute, and second hands to the appropriate positions
        hr.style.transform = `rotateZ(${hrs + (min / 12)}deg)`;
        mn.style.transform = `rotateZ(${min}deg)`;
        sc.style.transform = `rotateZ(${sec}deg)`;
    }, 1000); // Updating the clock every 1000 milliseconds (1 second)
    .clock-container {
        position: relative;
        width: 250px;
        height: 250px;
    }
            
    .clock-face {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: #333;
    }
            
    .clock-hand {
        position: absolute;
        background-color: white;
        height: 50%;
        top: 00%;
        left: 50%;
        transform-origin: 50% 100%;
        border-radius: 4px;
    }
            
    .hour-hand {
        width: 8px;
    }
            
    .minute-hand {
        width: 6px;
    }
            
    .second-hand {
        width: 4px;
    }
    <div class="clock-container">
         <div class="clock-face">
             <div class="clock-hand hour-hand"></div>
             <div class="clock-hand minute-hand"></div>
             <div class="clock-hand second-hand"></div>
         </div>
     </div>