reprahkcin
4/23/2020 - 11:31 PM

Interval Stopwatch with display

const theTimer = document.querySelector(".timer"); //DOM text element that will serve as display. Class of 'timer'

var timer = [0,0,0,0];
var timerRunning = false;

// Add leading zero to numbers 9 or below (purely for aesthetics):
function leadingZero(time) {
    if (time <= 9) {
        time = "0" + time;
    }
    return time;
}

// Run a standard minute/second/hundredths timer:
function runTimer() {
    let currentTime = leadingZero(timer[0]) + ":" + leadingZero(timer[1]) + ":" + leadingZero(timer[2]);
    theTimer.innerHTML = currentTime;
    timer[3]++;

    timer[0] = Math.floor((timer[3]/100)/60);
    timer[1] = Math.floor((timer[3]/100) - (timer[0] * 60));
    timer[2] = Math.floor(timer[3] - (timer[1] * 100) - (timer[0] * 6000));
}

//start the timer
function start() {
    if (timerRunning) {
        setInterval(runTimer, 10);
    }
}