JS DOM: Stopwatch

By Xah Lee. Date: . Last updated: .

Here is how to write a stopwatch.

Elapsed time: 0.0

Code

<div>

<p>Elapsed time:
<span id="output_rbFQx">0.0</span></p>

<button id="start_Qdnm6" type="button">Start</button>
<button id="stop_ZSxPC" type="button">Stop/Lap</button>
<button id="reset_fWZFm" type="button">Reset</button>

<script async src="js_stopwatch.js"></script>

</div>
"use strict";
{
    const start_Qdnm6 = document.getElementById("start_Qdnm6");
    const stop_ZSxPC = document.getElementById("stop_ZSxPC");
    const reset_fWZFm = document.getElementById("reset_fWZFm");
    const output_rbFQx = document.getElementById("output_rbFQx");
    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");
        output_rbFQx.firstChild.nodeValue = "0";
    };
    const updateDisplay = () => {
        output_rbFQx.firstChild.nodeValue = ((Date.now() - StartedDateTime.getTime()) / 1000).toFixed(2);
    };
    const fdisplay = (p_startStop) => {
        if (p_startStop === "start") {
            if (TimerIsOn) { }
            else {
                TimerIsOn = true;
                IntvID = setInterval(updateDisplay, TimerUpdateFrequency);
            }
        }
        else {
            if (IntvID !== null) {
                window.clearInterval(IntvID);
            }
            TimerIsOn = false;
            updateDisplay();
        }
    };
    start_Qdnm6.addEventListener("click", fstart);
    stop_ZSxPC.addEventListener("click", fstop);
    reset_fWZFm.addEventListener("click", freset);
}