stopwatch using javascript

In this article, we will learn how to build a simple stopwatch using html, css and javascript. I think the best approach to learn any technologies is by building app or services.

Learn the basic for the technology and jump onto building something that involves mostly with the technology you want to learn. You can start with something very simple and start increasing the level of complexity. For Javascript, I have created three projects and the learning curve is linear along with complexity of the project.

Create a Stopwatch using Javascript

You can perpetuate your knowledge of any technology by building multiple apps. This is the first part of learning javascript by building project.

As you know by the name, javascript allows you to build stopwatch that you have been using in your cellphone for day to day life. For this project you should have some basic understanding of html, css, javascript and how it can be used. If you do not have much experience, you do not need to worry as this project is very simple and anyone can understand it.

The entire process can be divided into three steps.

Create view layer(index.html) for Stopwatch

This is the presentation layer or the UI that is visible on the client side.

<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="style.css">
  <title>Stopwatch App</title>
</head>

<body>
    <div class="container">
      <h1>StopWatch</h1>
    </div>
    <div class="container">
      <div class="row stopwatch">
        <div class="col center-text">
          <p id="hours">00
          </p> :
        </div>
        <div class="col center-text">
          <p id="minutes">00
          </p>:
        </div>
        <div class="col center-text">
          <p id="seconds">00
          </p>:
        </div>
        <div class="col center-text">
          <p id="milliseconds">00
          </p>
        </div>
      </div>
      <div class="row buttons">
        <div class="col">
          <button onclick="startWatch()" class="btn start" id="stopwatch">Start</button>
          <button onclick="stopWatch()" class="btn stop" id="stopwatch">Stop</button>
          <button onclick="resetWatch()" class="btn reset" id="resetwatch">Reset</button>
        </div>
      </div>
    </div>
  <script type='text/javascript' src="script.js"></script>
</body>

</html>

Here we are defining a basic page with header, timer to display and buttons. I have given unique class name to elements so that we can use css to make it look better.

Style the stopwatch through style.css

body {
    background-color: #1B1B3A;
    color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-height: 80vh;
    font-family: 'Poppins',sans-serif;
    flex-direction:row; 
    justify-content:center; */
}

.row {
    display: flex;
    justify-content: center;
    align-items: center;
}

.container {
    display: inline;
    text-align: center;
}

h1 {
    font-size: 6rem;
    margin-top: 15px;
}

.start {
    background-color: green;
}

.stop {
    background-color: black;
}

.reset {
    background-color: red;
}

.btn {
    padding: 12px 12px;
    color: white;
    border: 2px solid;
    font-size: 1rem;
    width: 70px;
    margin-left: 10px;
}

.col {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.center-text {
    font-size: 5rem;
    line-height: 1;
    align-items: center;
    font-weight: bold;
}

p {
    margin: 0px;
}

.buttons {
    margin-top: 15px;
}

Add javascript (script.js) for functioning of our stopwatch

const hoursEl = document.getElementById('hours');
const minutesEl = document.getElementById('minutes');
const secondsEl = document.getElementById('seconds');
const milliseconds = document.getElementById('milliseconds');


let stopIntervalId; //value to track interval
let nowDate; //to track time
let carry = 0; // carry over value needed while working with time

//updates the time in stopwatch
function updateTime() {

    milliseconds.innerText = formatTime(parseMilliseconds
    (parseInt(milliseconds.innerText)+1));
    secondsEl.innerText = formatTime(addTime(parseInt(secondsEl.innerText)+carry));
    minutesEl.innerText = formatTime(parseInt(minutesEl.innerText)+carry);
    hoursEl.innerText = formatTime(parseInt(hoursEl.innerText)+carry);
}

//parse lowest second interval we have to second 
function parseMilliseconds(time) {
    carry = 0;
    if(time > 99) {
        carry = 1;
        return 0;
    } else {
        return time;
    }
}

//update second, minutes and hours as it hits 60
function addTime(time) {
    carry = 0;
    if(time > 59) {
        carry = 1;
        return 0;
    } else {
        return time;
    }
}

//start the watch
function startWatch() {
     //this commented code is to fix the bug when you click start button multiple times
    /*if(stopIntervalId !== undefined) {
        clearInterval(stopIntervalId);
    }*/
    carry = 0;    
    nowDate = new Date();
    stopIntervalId = setInterval(updateTime, 10);
}

//pause the watch
function stopWatch() {
    clearInterval(stopIntervalId);
}

//reset watch to 00
function resetWatch() {
    carry = 0;
    clearInterval(stopIntervalId);
    milliseconds.innerText = "00";
    secondsEl.innerText = "00";
    minutesEl.innerText = "00";
    hoursEl.innerText = "00";
}


//format time to look better even there is one digit
function formatTime(time) {
    return time < 10 ? `0${time}` : time;
}

Here we are defining the actual business logic for stopwatch and how to many it work.

Explanation

  • The actual logic of updating time is done through the command setInterval(updateTime, 10). If you want the actual milliseconds then you can update the time interval from 10 to 1. Similarly, if you want to update time to seconds then the interval should be 1000. updateTime is a function or the instructions which will run for every specified interval mentioned and this method is used to update time in the DOM or the UI elements.
  • As you can see in the first four lines of javascript code, we are returning elements that matches the id for hours, minutes, seconds and milliseconds.document.getElementById(‘hours’) points to the hour id/element we have in stopwatch. Any changes in hour fields has to be done by updating this element. Similarly, there are minutes, seconds and milliseconds(which is not actually milliseconds but 1/10 of second less than it). It will be easier to track time.
  • So, how do we actually update the fields then? It is done through milliseconds.innerText command. innerText updates text value inside the element defined by earlier command document.getElementById(‘milliseconds’).
  • For each start, stop and reset button, we have onclick(startWatch()) method defined with it which tells what to do when these buttons are clicked. Hence, with start button startWatch() method is called, which starts the stopwatch and updates the time in the index.html. Reset will reset all the values to 00 and stop will pause the stop watch. We can also use event listener for handling the button click. So, there are few options and it depends on you.

Let me know if you like the article through comments and if any improvements is required.