How to Create Stopwatch in Javascript

In this tutorial, you will learn how to create stopwatch using javascript.  We are going to use EasyTimer.js library. You can display time in seconds, minutes, hours and days.  It contains a lot of helpful methods such as start, stop, pause and reset.

I would recommend you to check out EasyTimer.js home page to know more about this and explore it a bit to get better understanding of its usage.  Simply download this library and add to your project using script tag in HTML file.  HTML, JS, and CSS code is given below.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div class="timerInfo">
        <h1 id="hours">00</h1>
        <h1 id="minutes">00</h1>
        <h1 id="seconds">00</h1>
        <h1 id="secTenth">00</h1>
    </div>

    <div class="buttons">
        <button id="start">Start</button>
        <button id="pause">Pause</button>
        <button id="stop">Stop</button>
    </div>

    <script src="easyTimer.js"></script>
    <script src="script.js"></script>
</body>
</html>

 

CSS:

.timerInfo, .buttons {
    display: flex;
    justify-content: center;
}

button {
    padding: 5px 10px;
    margin: 5px 10px;
}

h1+h1::before{
    content:':'
}

 

Javascript:

let startBtn = document.querySelector('#start');
let pauseBtn = document.querySelector('#pause');
let stopBtn = document.querySelector('#stop');


let hours = document.querySelector('#hours');
let minutes = document.querySelector('#minutes');
let seconds = document.querySelector('#seconds');
let secTenth = document.querySelector('#secTenth');


var timer = new easytimer.Timer();

timer.addEventListener('secondTenthsUpdated', () => {
    const obj = timer.getTimeValues();

    hours.innerText = obj.hours.toString().padStart(2, '0');
    minutes.innerText = obj.minutes.toString().padStart(2, '0');
    seconds.innerText = obj.seconds.toString().padStart(2, '0');
    secTenth.innerText = obj.secondTenths.toString().padStart(2, '0');
})

startBtn.addEventListener('click', () => {
    timer.start({
        precision: 'secondTenths'
    })
})

pauseBtn.addEventListener('click', () => {
    timer.pause();
})

stopBtn.addEventListener('click', () => {
    timer.stop();
})

 

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •