Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Digital clock not updating dynamically in JavaScript

I’m working on a web page that includes a digital clock and date display. However, I’ve encountered an issue where the digital clock doesn’t update dynamically; it only updates when the page is refreshed. Here’s the relevant JavaScript code I’m using:

 function updateDigitalClock() {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();

       
        hours = (hours < 10) ? '0' + hours : hours;
        minutes = (minutes < 10) ? '0' + minutes : minutes;
        seconds = (seconds < 10) ? '0' + seconds : seconds;

        var digitalClock = document.getElementById('digital-clock');
        digitalClock.innerHTML = hours + ':' + minutes + ':' + seconds;
    }

  
    function updateDate() {
        var now = new Date();
        var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        var dateElement = document.getElementById('date');
        dateElement.innerHTML = now.toLocaleDateString('en-US', options);
    }

Could someone please help me identify why the digital clock is not updating dynamically and suggest a solution?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason the digital clock doesn’t update dynamically is because the updateDigitalClock and updateDate functions are not called repeatedly. To fix this, you can use the setInterval function, which repeatedly calls these functions at specified intervals. Adding the following code to your JavaScript will update the clock and date every second:

setInterval(function() {
        updateDigitalClock();
        updateDate();
    }, 1000);

 updateDigitalClock();
 updateDate();

This ensures that the clock and date display are updated without needing to refresh the page.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading