create a stop watch with JavaScript

create a stop Watch with JavaScript

Create a Stop Watch with JavaScript

Learn how to create a stop watch with JavaScript.

Source code of HTML file.

<!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">
    <Script src="watch.js" defer></Script>
</head>
<body>
    <div class="container">
        <div class="wrapper">
            <div class="time">
            <span class="hours">00</span>
            <span class="colon">:</span>
            <span class="minutes">00</span>
            <span class="colon">:</span>
            <span class="seconds">00</span>
            <span class="colon ms-colon">:</span>
            <span class="milliseconds">00</span>
        </div>
        <div class="buttons">
            <button class="start">Start</button>
            <button class="stop">Stop</button>
            <button class="reset">Reset</button>
        </div>
        </div>
    </div>
</body>
</html>

Explanation.

Stopwatch Functionality (watch.js assumed):
  • Inside the container div, another div with the class wrapper holds the stopwatch elements.
  • A div with the class time displays the stopwatch time. It uses multiple span elements to represent hours, minutes, seconds, milliseconds, and colons.
    Initially, all these span elements display “00”.
  • Another div with the class buttons holds three buttons:
  • A button with the class start (likely to be used for starting the stopwatch).
  • A button with the class stop (likely to be used for stopping the stopwatch).
  • A button with the class reset (likely to be used for resetting the stopwatch to zero).
Functionality (JavaScript assumed):
  • The provided code snippet only shows the HTML structure. The JavaScript file (watch.js) will likely handle the stopwatch’s functionality.
  • It would likely use functions to:
  • Start the timer and update the displayed time on the webpage at regular intervals (e.g., milliseconds or seconds).
  • Stop the timer and freeze the displayed time.
  • Reset the timer back to 00:00:00.

Source code of CSS file

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.container{
    height: 100vh;
    width: 100%;
    background: #b9802a;
    display: flex;
    align-items: center;
    justify-content: center;
}
.wrapper{
    user-select: none;
}
.wrapper .time{
    height: 100px;
    background: #c9b996;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
}
.wrapper .time span{
    width: 100px;
    text-align: center;
    font-size: 40px;
    font-weight: 600;
    letter-spacing: 1px;
}
.time span.colon{
    width: 10px;
}
.time span.ms-colon,
.time span.milliseconds{
    color: #9b7235;
}
.container .buttons{
    display: flex;
    justify-content: center;
    margin-top: 18px;
}
.buttons button{
    padding: 6px 16px;
    outline: none;
    border: none;
    margin: 0 5px;
    color: #b9802a;
    font-size: 18px;
    background: #c9b996;
    border-radius: 4px;
}
.buttons button.active
{
    cursor: not-allowed;
    opacity: 0.5;
}

Explanation

Container Styles:
  • .container: This block defines styles for the element with the class container.
  • background: #b9802a;: This sets the background color of the container to a brownish orange (#b9802a).
  • display: flex;: This sets the field to apply a flexbox layout.
  • align-items: center;: This aligns the child elements of the box vertically in the middle.
  • justify-content: center;: This aligns the child elements of the container horizontally inside the middle.
Wrapper Styles:
  • .wrapper: This block defines styles for the element with the class wrapper.
  • user-select: none;: This prevents the user from selecting text within the wrapper element. This might be useful to avoid accidentally highlighting the displayed time.
Time Display Styles:
  • .wrapper .time: This block defines styles for the time element that is a child of the wrapper element.
  • height: 100px;: This sets the peak of the time display to a hundred pixels.
  • background: #c9b996;: This unit the heritage coloration of the time content to a lighter brownish orange (#c9b996).
  • display: flex;: This sets the time display to use a flexbox layout for positioning the child elements (hours, minutes, seconds, etc.).
  • align-items: center;: This aligns the child elements of the time display vertically in the center.
  • justify-content: center;: This aligns the child elements of the time display horizontally in the center.
  • border-radius: 5px;: This adds a slight rounded corner effect (5px) to the time display.
  • .wrapper .time span: This block defines styles for all span elements that are children of the time element.
    those represent individual components of the displayed time (hours, minutes, seconds, milliseconds, colons).
  • width: 100px;: This sets the width of on every occasion element to a hundred pixels.
  • text-align: center;: This centers the text inside on every occasion element.
  • font-size: 40px;: This sets the font size of the time to 40 pixels for a big and readable display.
  • font-weight: 600;: This sets the font weight to bold (six hundred) for a thicker and extra outstanding display.
  • letter-spacing: 1px;: This adds a moderate spacing (1px) among each character within the time display for higher readability.
  • .time span.colon: This block overrides styles for span elements with the class colon. These represent the colons separating hours, minutes, and seconds.
  • width: 10px;: This reduces the width of the colon elements to 10 pixels compared to the wider time elements (hours, minutes, seconds, milliseconds).
  • .time span.ms-colon, .time span.milliseconds: This block applies styles to span elements with the classes ms-colon and milliseconds. These likely represent the colon and milliseconds part of the display.
  • color: #9b7235;: This sets the color of the milliseconds to display to a darker brownish orange (#9b7235). This might be used to differentiate milliseconds from the rest of the time.
Button Styles:
  • .container .buttons: This block defines styles for the buttons element that is a child of the container element.
  • display: flex;: This sets the buttons element to use a flexbox layout for positioning the buttons.

Source code of JavaScript file

let hr = min = sec = ms = "0" + 0,
    startTimer;
const startBtn=document.querySelector(".start");
const stopBtn=document.querySelector(".stop");
const resetBtn=document.querySelector(".reset");
startBtn.addEventListener("click" ,start);
stopBtn.addEventListener("click" ,stop);
resetBtn.addEventListener("click" ,reset);
function start()
{
    startBtn.classList.add("active");
    stopBtn.classList.remove("active");
    startTimer = setInterval(()=>{
        ms++
        ms= ms<10 ? "0" + ms : ms;
        if(ms == 100)
        {
            sec++;
            sec= sec<10 ? "0" + sec : sec;
            ms = "0" + 0;
        }
        if(sec == 60)
        {
            min++;
            min= min<10 ? "0" + min : min;
            sec = "0" + 0;
        }
        if(min == 60)
        {
            hr++;
            hr= hr<10 ? "0" + hr : hr;
            min = "0" + 0;
        }
        putValue();
    },10);
}
function stop()
{
    startBtn.classList.remove("active");
    stopBtn.classList.add("active");
    clearInterval(startTimer);
}
function reset()
{
    startBtn.classList.remove("active");
    stopBtn.classList.remove("active");
    clearInterval(startTimer);
    hr = min = sec = ms = "0" + 0;
    putValue();
}
function putValue()
{
    document.querySelector(".milliseconds").innerText =ms;
    document.querySelector(".seconds").innerText =sec;
    document.querySelector(".minutes").innerText =min;
    document.querySelector(".hours").innerText =hr;
}

 

 

Explanation.

Variable Initialization:
  • let hr = min = sec = ms = “0” + 0, startTimer;
  • This line declares and initializes several variables:
  • hr, min, sec, and ms: These variables store the time values (hours, minutes, seconds, milliseconds) as strings. They are initialized to “00” using a trick to ensure a leading zero for single-digit values. Adding 0 to a string converts it to a number, and then adding that number back to the string “0” prepends a zero if the original value was less than 10.
  • startTimer: This variable will hold an identifier used to stop the timer later. It’s initially undefined.
Button References:
  • const startBtn = document.querySelector(“.start”);
  • This line finds the button element with the class start on the webpage and stores a reference to it in the constant startBtn.
  • Similar lines are used for stopBtn (stop button) and resetBtn (reset button) to store references to their respective button elements.
Event Listeners:
  • startBtn.addEventListener(“click”, start);
  • This line attaches an event listener to the startBtn button.
  • The listener listens for the “click” event on the button.
  • When the button is clicked, it calls the function named start.
  • Similar lines are used for stopBtn (calling stop function) and resetBtn (calling reset function). This way, clicking the respective buttons triggers their corresponding functions.
start() function:
  • This feature is performed while the start button is clicked.
  • startBtn.classList.add(“active”);: This line adds the class “active” to the startBtn element. This might be used with CSS to visually indicate the button is currently active (started).
  • stopBtn.classList.remove(“active”);: This removes the “active” class from the stopBtn element. This might be used with CSS to visually indicate it’s not active (stopped).
  • startTimer = setInterval(() => { … }, 10);
  • This line sets up a timer using setInterval.
  • setInterval takes two arguments: a function to call repeatedly and the time interval (in milliseconds) between calls.
    here, it calls a nameless feature (described as the use of an arrow characteristic) every 10 milliseconds (1/100th of a 2nd).
  • Inside the anonymous function:
  • ms++: This increments the milliseconds by 1.
  • ms = ms < 10 ? “0” + ms: ms;: This ensures a leading zero for milliseconds in the displayed time. If ms is less than 10, a zero is prepended.
  • The logic then checks if ms reaches 100 (100 milliseconds):
  • if (ms == 100) { … }: If ms is 100, it increments the seconds (sec) by 1 and resets ms to “00”.
  • Similar logic is applied for sec reaching 60 (incrementing minutes and resetting seconds) and min reaching 60 (incrementing hours and resetting minutes).
  • Each time a unit is incremented, leading zeros are ensured using the same logic as for milliseconds.
    putValue();: This line calls the putValue function to update the displayed time on the webpage, reflecting the changes in milliseconds, seconds, minutes, and hours.
stop() function:
  • This function is called when the stop button is clicked.
  • startBtn.classList.remove(“active”);: This removes the “active” class from the start button.
  • stopBtn.classList.add(“active”);: This adds the “active” magnificence to the stop button, possibly for visible remarks.
  • clearInterval(startTimer);: This line is crucial. It stops the timer set up in the start function using clearInterval. It takes the identifier stored in startTimer (which holds the interval ID) and cancels the repeated execution of the anonymous function within startTimer. This effectively pauses the stopwatch.
Reset() function:
  • This function is called when the reset button is clicked.
  • It resets the button styles and stops the timer similar to the stop function.
  • Additionally, it resets the hr, min, sec to 00:00:00.
Thanks for reading this Article.
How to create a stop watch with JavaScript?
by Sparkify Solutions.

Leave a Comment

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