Create a Stopwatch using JavaScript with Source Code

  • Post author:
  • Post comments:0 Comments
  • Reading time:148 mins read

Step into the world of precise timekeeping with our Stopwatch project using JavaScript. In this article, we’ll guide you through the development process and provide the source code to create a functional and user-friendly stopwatch, whether for personal use or integration into various timing-related applications.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StopWatch</title>
    <link rel="stylesheet" href="./style.css" type="text/css">
</head>
<body>
    <div class="container">
        <h1 class="title">StopWatch</h1>
        <div class="timer-box">
            <p class="timer">00:00:00</p>
        </div>
        <div class="btn-wrapper">
            <button class="btn">
                <img class="btn-svg" id="btn-reset" src="./images/stop.svg" alt="reset">
            </button>
            <button class="btn">
                <img class="btn-svg" id="btn-play" src="./images/play-button-arrowhead.svg" alt="play">
                <img class="btn-svg" id="btn-pause" src="./images/pause.svg" alt="pause">
            </button>
        </div>
    </div>

    <script src="./script.js" type="text/javascript"></script>
</body>
</html>

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
html,
body {
    font-family: lato, sans-serif, Arial;
    font-size: 10px;  /* 1rem = 10px */
    min-height: 100vh;
}
body {
    background: linear-gradient(45deg, #5f5fc4, #062d25, #259f88);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.container {
    width: 30rem;
    height: 35rem;
    background: #eeeeee;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    border-radius: 5px;
    box-shadow: 0 0 8px 4px rgba(0,0,0,0.4);
    padding: 2rem;
}
.timer-box {
    background: white;
    border: 1px solid black;
    border-radius: 5px;
    padding: 1rem;
}
.timer {
    font-size: 4rem;
    font-weight: lighter;
}
.btn-wrapper {
    display: flex;
    justify-content: space-between;
    width: 15rem;
}
.btn {
    cursor: pointer;
    background: transparent;
    border: none;
    outline: none;
    width: 4rem;
}
.btn-svg {
    width: 4rem;
}
#btn-play{
    display: block;
}
#btn-pause{
    display: none;
}

//DOM Elements

const playButton = document.getElementById('btn-play');
const pauseButton = document.getElementById('btn-pause');
const resetButton = document.getElementById('btn-reset');
const timer = document.querySelector('.timer');

// CONVERTING TIME TO STRING

function timeToString(time){
    // assume time is 10000000 ms, then
    let differenceInHours = time / 3600000; // 2.777
    let hr = Math.floor(differenceInHours); //2

    let differenceInMinutes = (differenceInHours - hr)*60;  // 46.666
    let min = Math.floor(differenceInMinutes); // 46

    let differenceInSeconds = (differenceInMinutes - min)*60; // 39.99
    let sec = Math.floor(differenceInSeconds); // 39

    let differenceInMilliseconds = (differenceInSeconds - sec)*100; //99.99  /* multiplied it by 100 not 1000 to make it two digit */
    let ms = Math.floor(differenceInMilliseconds); // 99

    //but we want our format to be 02:46:39 , not 2:46:39 ---> for that use padStart()

    let formattedmin = min.toString().padStart(2, '0');
    let formattedsec = sec.toString().padStart(2, '0');
    let formattedms = ms.toString().padStart(2, '0');

    //now we can return the time in required format
    return `${formattedmin}:${formattedsec}:${formattedms}`;
}

let startTime;
let elapsedTime = 0;
let timerInterval;

function displayInTimer(str){
    timer.innerHTML = str;
}

function play(){
    startTime = Date.now() - elapsedTime;
    timerInterval = setInterval(function printTime(){
        elapsedTime = Date.now() - startTime;
        displayInTimer(timeToString(elapsedTime));
    },10);
    toggleButtons("PAUSE");
}

function pause(){
    clearInterval(timerInterval);
    toggleButtons("PLAY");
}

function reset(){
    clearInterval(timerInterval);
    displayInTimer('00:00:00');
    elapsedTime = 0;
    toggleButtons("PLAY");
}
function toggleButtons(Key) {
    if(Key === 'PLAY'){
        playButton.style.display = 'block';
        pauseButton.style.display = 'none';
    } else {
        playButton.style.display = 'none';
        pauseButton.style.display = 'block';
    }
}


//EVENT LISTENERS

playButton.addEventListener('click', play);
pauseButton.addEventListener('click',pause);
resetButton.addEventListener('click', reset);

Leave a Reply