JS: Stopwatch

By Xah Lee. Date: . Last updated: .

Here's how to write a stopwatch.

Elapsed time: 0.0

Here's the HTML code:

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

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

Here's JavaScript ES2015 code.

{

const display_ele = 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");
    display_ele.firstChild.nodeValue = "0";
});

const updateDisplay = (() => {
    display_ele.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();
    }
});

document.getElementById("start08637").addEventListener("click", fstart , false);

document.getElementById("stop44129").addEventListener("click", fstop , false);

document.getElementById("reset96523").addEventListener("click", freset , false);

}

Simple DOM Examples

  1. JS: Change CSS
  2. DOM: Change Element's Content
  3. DOM: Create HTML Element
  4. DOM: Remove HTML Element

  1. JS: document.write
  2. JS: Image Rollover
  3. JS: Pop-up New Window
  4. JS: Digital Clock
  5. JS: Stopwatch
  6. JS: Fade a Element
  7. JS: Fade a Element Using CSS Transition
  8. JavaScript UI: Shake Element
  9. JS: How to Create Tooltip
  10. JS: Falling Snow Effect
  11. JavaScript Floating Box Following Scroll
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon