How To Create StopWatch Using HTML CSS And JavaScript

In this article, we will learn about how to create Stopwatch.

Step-1: Create Html Code in the index.html file.

<div class="wrapper">
    <h4>Stopwatch</h4>  
    <p><span id="seconds">00</span>:<span id="tens">00</span></p>
    <button id="button-start" class="btn-success">Start</button>
    <button id="button-stop" class="btn-danger">Stop</button>
    <button id="button-reset" class="btn-warning">Reset</button>
</div>

Step-2: Add CSS in<style>….</style> tag on index.html file.

body {
       font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
       height: 100%;
   }

   .wrapper {
       width: 800px;
       margin: 30px auto;
       color: $white;
       text-align: center;
   }

   h1, h2, h3 {
       font-family: 'Roboto', sans-serif;
       font-weight: 100;
       font-size: 2.6em;
       text-transform: uppercase;
   }

   #seconds, #tens {
       font-size: 2em;
   }

Step-3: Add Javascript in<script>….</script> tag on index.html file.

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;
            }
        }
    }

Output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories