How to create a stopwatch using JavaScript?

3 years ago

In this tutorial, I will show you how to create a Javascript stopwatch, which has a start, stop and reset button. JavaScript stopwatch can be implemented using the JavaScript timing methods which are executed in time intervals. JavaScript timing methods automate a particular task to be done on the fly without you having to click a button or call an event. To create this type of app on your desktop, follow the following steps.

Step 1: Create index.html on your own folder.

Step 2: Copy and paste the following code in index.html file.

<html>
<head>
    <title>JavaScript</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="main"> 
        <div id="stopwatch">
            00:00:00
        </div>
        <ul id="buttons">
            <li><button onclick="startTimer()">Start</button></li>
            <li><button onclick="stopTimer()">Stop</button></li>
            <li><button onclick="resetTimer()">Reset</button></li>
        </ul>
    </div>
    <script src="script.js"></script>
</body>
</html>

 

Step 3: Now, It's time to design your view. For this create another file named style.css and copy and paste the following CSS scripts into the style.css file. 

#main {
    background-color: orange;
    margin: 50px 120px 50px 180px;
    padding: 80px;
    text-align: center;
    border: 5px outset green;
}

button {
    padding: 30px;
    width: 90px;
    border: 3px solid white;
    background: brown;
    color: white;
    cursor: pointer;
    outline: none;
}

button:hover{
    background: green;
}

#stopwatch {
    font-size: 90px;
    color: white;
    margin-left: 35px;
}

#buttons li {
    text-align: center;
    display: inline;
}

 

 

Step 4: Finally we should use some JavaScript code to make this app workable. For that copy the following codes and paste them into script.js file. 

const timer = document.getElementById('stopwatch');

var hr = 0;
var min = 0;
var sec = 0;
var stoptime = true;

function startTimer() {
  if (stoptime == true) {
        stoptime = false;
        timerCycle();
    }
}
function stopTimer() {
  if (stoptime == false) {
    stoptime = true;
  }
}

function timerCycle() {
    if (stoptime == false) {
    sec = parseInt(sec);
    min = parseInt(min);
    hr = parseInt(hr);

    sec = sec + 1;

    if (sec == 60) {
      min = min + 1;
      sec = 0;
    }
    if (min == 60) {
      hr = hr + 1;
      min = 0;
      sec = 0;
    }

    if (sec < 10 || sec == 0) {
      sec = '0' + sec;
    }
    if (min < 10 || min == 0) {
      min = '0' + min;
    }
    if (hr < 10 || hr == 0) {
      hr = '0' + hr;
    }

    timer.innerHTML = hr + ':' + min + ':' + sec;

    setTimeout("timerCycle()", 1000);
  }
}

function resetTimer() {
    hr = 0;
    min = 0;
    sec = 0;
    timer.innerHTML = '00:00:00';
    stoptime = true;
}

Note: Put all these 3 files (index.html, style.css, and script.js) file into the same directory. 

  2168