JS: Stopwatch

By Xah Lee. Date: . Last updated: .

Here is how to write a stopwatch.

Elapsed time: 0.0

Here is the HTML code:

<button id="start08637" type="button">Start</button>
<button id="stop44129" type="button">Stop/Lap</button>
<button id="reset96523" type="button">Reset</button>

Here is JavaScript ES2015 code.

{

const start08637 = document.getElementById("start08637");
const stop44129 = document.getElementById("stop44129");
const reset96523 = document.getElementById("reset96523");
const display29700 = document.getElementById("display29700");

let StartedDateTime = new Date;
let ElapsedTime = 0;
let IntvID = null;
let TimerIsOn = false;
let TimerUpdateFrequency = 100; // millisecond

const fstart = (() => {
    StartedDateTime = new Date;
    fdisplay("start");
})

const fstop = (() => {
    ElapsedTime = Date.now () - StartedDateTime.getTime();
    fdisplay("stop");
});

const freset = (() => {
    ElapsedTime = 0;
    fdisplay("stop");
    display29700.firstChild.nodeValue = "0";
});

const updateDisplay = (() => {
    display29700.firstChild.nodeValue = ( (Date.now () - StartedDateTime.getTime()) / 1000 ).toFixed (2);
});

const fdisplay = ((p_startStop) => {
    if (p_startStop === "start") {
        if ( TimerIsOn === true ) {}
        else {
            TimerIsOn = true;
            IntvID = setInterval( updateDisplay , TimerUpdateFrequency);
        }
    } else {
        if (IntvID !== null ) {
            window.clearInterval(IntvID);
        }
        TimerIsOn = false;
        updateDisplay();
    }
});

start08637.addEventListener("click", fstart, false);
stop44129.addEventListener("click", fstop, false);
reset96523.addEventListener("click", freset, false);

}