[javascript] How to create a stopwatch using JavaScript?

if(stopwatch >= track[song].duration)

track[song].duration finds the duration of a soundcloud track.

I am looking to create a stopwatch function that starts counting milliseconds when you click on the swap ID stopwatch so that when the function has been "clicked" for a certain amount of time the if function will do something. In my case replace an image. And also that the function will reset it itself when clicked again.

so like stopwatch = current time - clicked time How can I set up the clicked time

current time = new Date().getTime(); ? And is this in milliseconds?

$('#swap').click(function()...

This question is related to javascript jquery

The answer is


A simple and easy clock for you and don't forget me ;)

_x000D_
_x000D_
var x;_x000D_
var startstop = 0;_x000D_
_x000D_
function startStop() { /* Toggle StartStop */_x000D_
_x000D_
  startstop = startstop + 1;_x000D_
_x000D_
  if (startstop === 1) {_x000D_
    start();_x000D_
    document.getElementById("start").innerHTML = "Stop";_x000D_
  } else if (startstop === 2) {_x000D_
    document.getElementById("start").innerHTML = "Start";_x000D_
    startstop = 0;_x000D_
    stop();_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function start() {_x000D_
  x = setInterval(timer, 10);_x000D_
} /* Start */_x000D_
_x000D_
function stop() {_x000D_
  clearInterval(x);_x000D_
} /* Stop */_x000D_
_x000D_
var milisec = 0;_x000D_
var sec = 0; /* holds incrementing value */_x000D_
var min = 0;_x000D_
var hour = 0;_x000D_
_x000D_
/* Contains and outputs returned value of  function checkTime */_x000D_
_x000D_
var miliSecOut = 0;_x000D_
var secOut = 0;_x000D_
var minOut = 0;_x000D_
var hourOut = 0;_x000D_
_x000D_
/* Output variable End */_x000D_
_x000D_
_x000D_
function timer() {_x000D_
  /* Main Timer */_x000D_
_x000D_
_x000D_
  miliSecOut = checkTime(milisec);_x000D_
  secOut = checkTime(sec);_x000D_
  minOut = checkTime(min);_x000D_
  hourOut = checkTime(hour);_x000D_
_x000D_
  milisec = ++milisec;_x000D_
_x000D_
  if (milisec === 100) {_x000D_
    milisec = 0;_x000D_
    sec = ++sec;_x000D_
  }_x000D_
_x000D_
  if (sec == 60) {_x000D_
    min = ++min;_x000D_
    sec = 0;_x000D_
  }_x000D_
_x000D_
  if (min == 60) {_x000D_
    min = 0;_x000D_
    hour = ++hour;_x000D_
_x000D_
  }_x000D_
_x000D_
_x000D_
  document.getElementById("milisec").innerHTML = miliSecOut;_x000D_
  document.getElementById("sec").innerHTML = secOut;_x000D_
  document.getElementById("min").innerHTML = minOut;_x000D_
  document.getElementById("hour").innerHTML = hourOut;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
/* Adds 0 when value is <10 */_x000D_
_x000D_
_x000D_
function checkTime(i) {_x000D_
  if (i < 10) {_x000D_
    i = "0" + i;_x000D_
  }_x000D_
  return i;_x000D_
}_x000D_
_x000D_
function reset() {_x000D_
_x000D_
_x000D_
  /*Reset*/_x000D_
_x000D_
  milisec = 0;_x000D_
  sec = 0;_x000D_
  min = 0_x000D_
  hour = 0;_x000D_
_x000D_
  document.getElementById("milisec").innerHTML = "00";_x000D_
  document.getElementById("sec").innerHTML = "00";_x000D_
  document.getElementById("min").innerHTML = "00";_x000D_
  document.getElementById("hour").innerHTML = "00";_x000D_
_x000D_
}
_x000D_
<h1>_x000D_
  <span id="hour">00</span> :_x000D_
  <span id="min">00</span> :_x000D_
  <span id="sec">00</span> :_x000D_
  <span id="milisec">00</span>_x000D_
</h1>_x000D_
_x000D_
<button onclick="startStop()" id="start">Start</button>_x000D_
<button onclick="reset()">Reset</button>
_x000D_
_x000D_
_x000D_


Please see stopwatch.js for a very clean and simple Vanilla Javascript ES6 solution.


This is my simple take on this question, I hope it helps someone out oneday, somewhere...

_x000D_
_x000D_
let output = document.getElementById('stopwatch');
let ms = 0;
let sec = 0;
let min = 0;

function timer() {
    ms++;
    if(ms >= 100){
        sec++
        ms = 0
    }
    if(sec === 60){
        min++
        sec = 0
    }
    if(min === 60){
        ms, sec, min = 0;
    }

    //Doing some string interpolation
    let milli = ms < 10 ? `0`+ ms : ms;
    let seconds = sec < 10 ? `0`+ sec : sec;
    let minute = min < 10 ? `0` + min : min;

    let timer= `${minute}:${seconds}:${milli}`;
    output.innerHTML =timer;
};
//Start timer
function start(){
 time = setInterval(timer,10);
}
//stop timer
function stop(){
    clearInterval(time)
}
//reset timer
function reset(){
    ms = 0;
    sec = 0;
    min = 0;

    output.innerHTML = `00:00:00`
}
const startBtn = document.getElementById('startBtn');
const stopBtn =  document.getElementById('stopBtn');
const resetBtn = document.getElementById('resetBtn');

startBtn.addEventListener('click',start,false);
stopBtn.addEventListener('click',stop,false);
resetBtn.addEventListener('click',reset,false);
_x000D_
    <p class="stopwatch" id="stopwatch">
        <!-- stopwatch goes here -->
    </p>
    <button class="btn-start" id="startBtn">Start</button>
    <button class="btn-stop" id="stopBtn">Stop</button>
    <button class="btn-reset" id="resetBtn">Reset</button>
_x000D_
_x000D_
_x000D_


Solution by Mosh Hamedani

Creating a StopWatch function constructor.

Define 4 local variables

  1. startTime
  2. endTime
  3. isRunning
  4. duration set to 0

Next create 3 methods

  1. start
  2. stop
  3. reset

start method

  • check if isRunning is true if so throw an error that start cannot be called twice.
  • set isRunning to true
  • assign the current Date object to startTime.

stop method

  • check if isRunning is false if so throw an error that stop cannot be called twice.
  • set isRunning to false
  • assign the current Date object to endTime.
  • calculate the seconds by endTime and startTime Date object
  • increment duration with seconds

reset method:

  • reset all the local variables.

Read-only property

if you want to access the duration local variable you need to define a property using Object.defineProperty. It's useful when you want to create a read-only property.

Object.defineProperty takes 3 parameters

  • the object which to define a property (in this case the current object (this))
  • the name of the property
  • the value of the key property.

  • We want to create a Read-only property so we pass an object as a value. The object contain a get method that return the duration local variable. in this way we cannot change the property only get it.

The trick is to use Date() object to calculate the time.

Reference the code below

function StopWatch() {


let startTime,
    endTime,
    isRunning,
    duration = 0;

  this.start = function () {
    if (isRunning) throw new Error("StopWatch has already been started.");

    isRunning = true;

    startTime = new Date();
  };



this.stop = function () {
    if (!isRunning) throw new Error("StopWatch has already been stop.");

    isRunning = false;

    endTime = new Date();

    const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
    duration += seconds;
  };

  this.reset = function () {
    duration = 0;
    startTime = null;
    endTime = null;
    isRunning = false;
  };

  Object.defineProperty(this, "duration", {
    get: function () {
      return duration;
    },
  });
}

const sw = new StopWatch();

well after a few modification of the code provided by mace,i ended up building a stopwatch. https://codepen.io/truestbyheart/pen/EGELmv

  <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Stopwatch</title>
    <style>
    #center {
     margin: 30%  30%;
     font-family: tahoma;
     }
    .stopwatch {
         border:1px solid #000;
         background-color: #eee;
         text-align: center;
         width:656px;
         height: 230px;
         overflow: hidden;
     }
     .stopwatch span{
         display: block;
         font-size: 100px;
     }
     .stopwatch p{
         display: inline-block;
         font-size: 40px;
     }
     .stopwatch a{
       font-size:45px;
     }
     a:link,
     a:visited{
         color :#000;
         text-decoration: none;
         padding: 12px 14px;
         border: 1px solid #000;
     }
    </style>
  </head>
  <body>
      <div id="center">
            <div class="timer stopwatch"></div>
      </div>

    <script>
      const Stopwatch = function(elem, options) {
        let timer = createTimer(),
          startButton = createButton("start", start),
          stopButton = createButton("stop", stop),
          resetButton = createButton("reset", reset),
          offset,
          clock,
          interval,
          hrs = 0,
          min = 0;

        // default options
        options = options || {};
        options.delay = options.delay || 1;

        // append elements
        elem.appendChild(timer);
        elem.appendChild(startButton);
        elem.appendChild(stopButton);
        elem.appendChild(resetButton);

        // initialize
        reset();

        // private functions
        function createTimer() {
          return document.createElement("span");
        }

        function createButton(action, handler) {
          if (action !== "reset") {
            let a = document.createElement("a");
            a.href = "#" + action;
            a.innerHTML = action;
            a.addEventListener("click", function(event) {
              handler();
              event.preventDefault();
            });
            return a;
          } else if (action === "reset") {
            let a = document.createElement("a");
            a.href = "#" + action;
            a.innerHTML = action;
            a.addEventListener("click", function(event) {
              clean();
              event.preventDefault();
            });
            return a;
          }
        }

        function start() {
          if (!interval) {
            offset = Date.now();
            interval = setInterval(update, options.delay);
          }
        }

        function stop() {
          if (interval) {
            clearInterval(interval);
            interval = null;
          }
        }

        function reset() {
          clock = 0;
          render(0);
        }

        function clean() {
          min = 0;
          hrs = 0;
          clock = 0;
          render(0);
        }

        function update() {
          clock += delta();
          render();
        }

        function render() {
          if (Math.floor(clock / 1000) === 60) {
            min++;
            reset();
            if (min === 60) {
              min = 0;
              hrs++;
            }
          }
          timer.innerHTML =
            hrs + "<p>hrs</p>" + min + "<p>min</p>" + Math.floor(clock / 1000)+ "<p>sec</p>";
        }

        function delta() {
          var now = Date.now(),
            d = now - offset;

          offset = now;
          return d;
        }
      };

      // Initiating the Stopwatch
      var elems = document.getElementsByClassName("timer");

      for (var i = 0, len = elems.length; i < len; i++) {
        new Stopwatch(elems[i]);
      }
    </script>
  </body>
</html>

Two native solutions

  • performance.now --> Call to ... took 6.414999981643632 milliseconds.
  • console.time --> Call to ... took 5.815 milliseconds

The difference between both is precision.

For usage and explanation read on.



Performance.now (For microsecond precision use)

_x000D_
_x000D_
    var t0 = performance.now();
    doSomething();
    var t1 = performance.now();

    console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
            
    function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
    }
_x000D_
_x000D_
_x000D_

performance.now

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().



console.time

Example: (timeEnd wrapped in setTimeout for simulation)

_x000D_
_x000D_
console.time('Search page');
  doSomething();
console.timeEnd('Search page');
 

 function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
 }
_x000D_
_x000D_
_x000D_

You can change the Timer-Name for different operations.


function StopWatch() {
    let startTime, endTime, running, duration = 0
    
    this.start = () => {
        if (running) console.log('its already running')
        else {
            running = true
            startTime = Date.now()
        }
    }

    this.stop = () => {
        if (!running) console.log('its not running!')
        else {
            running = false
            endTime = Date.now()

            const seconds = (endTime - startTime) / 1000
            duration += seconds
        }
    }

    this.restart = () => {
        startTime = endTime = null
        running = false
        duration = 0
    }
    
    Object.defineProperty(this, 'duration', {
        get: () => duration.toFixed(2)
    })

}

const sw =  new StopWatch()

sw.start()
sw.stop()

sw.duration