A Minimal Pure Javascript Stopwatch

Category: Date & Time , Javascript | August 25, 2014
Author:cathydutton
Views Total:11,092 views
Official Page:Go to website
Last Update:August 25, 2014
License:MIT

Preview:

A Minimal Pure Javascript Stopwatch

Description:

A simple lightweight Javascript stopwatch which allows you to count up from zero with start, pause, resume and stop controls. Created by cathydutton.

Basic Usage:

Create the Html for a stopwatch.

<p><span id="seconds">00</span>:<span id="tens">00</span></p>

Create some controls for the stopwatch.

<button id="button-start">Start</button>
<button id="button-stop">Stop</button>
<button id="button-reset">Reset</button>

The Javascript to enable the stopwatch.

window.onload = function () {
  
  var seconds = 00; 
  var tens = 00; 
  var appendTens = document.getElementById("tens")
  var appendSeconds = document.getElementById("seconds")
  var buttonStart = document.getElementById('button-start');
  var buttonStop = document.getElementById('button-stop');
  var buttonReset = document.getElementById('button-reset');
  var Interval ;
  buttonStart.onclick = function() {
    
     clearInterval(Interval);
     Interval = setInterval(startTimer, 10);
  }
  
    buttonStop.onclick = function() {
       clearInterval(Interval);
  }
  
  buttonReset.onclick = function() {
     clearInterval(Interval);
    tens = "00";
  	seconds = "00";
    appendTens.innerHTML = tens;
  	appendSeconds.innerHTML = seconds;
  }
  
   
  
  function startTimer () {
    tens++; 
    
    if(tens < 9){
      appendTens.innerHTML = "0" + tens;
    }
    
    if (tens > 9){
      appendTens.innerHTML = tens;
      
    } 
    
    if (tens > 99) {
      console.log("seconds");
      seconds++;
      appendSeconds.innerHTML = "0" + seconds;
      tens = 0;
      appendTens.innerHTML = "0" + 0;
    }
    
    if (seconds > 9){
      appendSeconds.innerHTML = seconds;
    }
  
  }
  
}

You Might Be Interested In:


2 thoughts on “A Minimal Pure Javascript Stopwatch

  1. Garry Hicks

    Hey there! What would be your solution to this timer only running when focused on this page? If you leave the page, this will pause the count.

    Reply

Leave a Reply