JSFiddle - React, Tailwind, and code Playground

by jfriend00

HTML

<span id="curTime"></span> (real time so you can see the seconds - for demo purposes) <br>
<span id="time"></span> (time that is only updated on the minute change)

JavaScript

function twoDigits(val) {
    val = val + "";
    if (val.length < 2) {
        val = "0" + val;
    }
    return val;
}

function update(id, showSeconds) {
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    if (!showSeconds) {
        // round the minutes
        if (seconds > 30) {
            ++minutes;
            if (minutes >= 60) {
                minutes -= 60;
                ++hours;
                if (hours >= 24) {
                    hours = 0;
                }
            }
        }
    }
    var str = (hours) + ":" + twoDigits(minutes);
    if (showSeconds) {
        str += ":" + twoDigits(seconds);
    }
    document.getElementById(id).innerHTML = str;
}

function runClock() {
    var now = new Date();
    var timeToNextTick = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
    setTimeout(function() {
        update("time");
        runClock();
    }, timeToNextTick);
}  

// start it
update("time");
runClock();

// This part for demo purposes only
// so we can see exactly when the other clock updates
setInterval(function() {
    update("curTime", true);
}, 50);