JSFiddle - React, Tailwind, and code Playground

by BurpmanJunior

HTML

<div>
    <p><strong>Millisecond Offset Correcting</strong></p>
    <span id="hh"></span>:<span id="mm"></span>:<span id="ss"></span>:<span id="ms"></span> <span id="counter"></span>
    <p id="offset"></p>
</div>

<div>
    <p><strong>setInterval</strong> (note the millisecond drift)</p>
    <span id="hh2"></span>:<span id="mm2"></span>:<span id="ss2"></span>:<span id="ms2"></span> <span id="counter2"></span>
    <p id="offset2"></p>
</div>

CSS

body {
    font-size: 4vh;
    text-align: center;
    font-family: monospace;
    margin-top: 28vh;
    background-color: #473554;
    color: #a69dad;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3);
}

div{
    margin-bottom: 10vh;
}
div:last-child{
    margin-bottom: 0;
}

JavaScript

/**
 * SELF CORRECTING SECOND TIMER
 */

function $(selector) { return document.querySelector(selector) }

var intClock = false;

var hh = hh || $('#hh'),
    mm = mm || $('#mm'),
    ss = ss || $('#ss'),
    ms = ms || $('#ms'),
    oo = oo || $('#offset'),
    counter = counter || $('#counter'),
	i1 = 0;

var hh2 = hh2 || $('#hh2'),
    mm2 = mm2 || $('#mm2'),
    ss2 = ss2 || $('#ss2'),
    ms2 = ms2 || $('#ms2'),
    oo2 = oo2 || $('#offset2'),
    counter2 = counter2 || $('#counter2'),
	i2 = 0;

function update(){
    var date = new Date();
    
    var o = 1000 - date.getMilliseconds();
    o = o < 10 ? 1000 : o; // Forward overlap fix
    setTimeout(update, o);
    
    if(!intClock){
        intClock = window.setInterval(updateClock, 1000);
    }
    
    oo.textContent = 'Offset: ' + o;
    
    counter.innerHTML = '<strong>' + i1 + '</strong>';
    i1++;
    
    date = date || new Date();
    
    hh.textContent = (date.getHours() < 10 ? '0' : '') + date.getHours();
    mm.textContent = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
    ss.textContent = (date.getSeconds() < 10 ? '0' : '') + date.getSeconds();
    var nms = Math.floor(date.getMilliseconds() / 10);
    ms.textContent = (nms < 10 ? '0' : '') + nms;
}

function updateClock(date){
    date = date || new Date();
    
    counter2.innerHTML = '<strong>' + i2 + '</strong>';
    i2++;
    
    hh2.textContent = (date.getHours() < 10 ? '0' : '') + date.getHours();
    mm2.textContent = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
    ss2.textContent = (date.getSeconds() < 10 ? '0' : '') + date.getSeconds();
    var nms = Math.floor(date.getMilliseconds() / 10);
    ms2.textContent = (nms < 10 ? '0' : '') + nms;
}

update();
updateClock();