Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The setTimeout( ) Method
2.1.
Structure Of The setTimeout( ) Method
2.2.
Example: To Calculate Milliseconds
3.
Creating A Stop Watch
3.1.
Example: JavaScript Code for startwatch.js
4.
The clearTimeout( ) Method
4.1.
Working
5.
Example: Stop The Time – stopwatch.js
6.
The CSS
7.
The HTML
8.
Frequently Asked Questions
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

How to Create a Stop Watch In Javascript

Author Akash
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

JavaScript stopwatch or, rather, stop down timer can be implemented using the JavaScript timing methods that will see further in this article in detail, executed in time intervals.

Javascript methods automate a particular task to be done on the fly without you having to click a button or call an event.

Let's start with the Timing methods in detail without wasting much time.

The setTimeout( ) Method

Syntax:

setTimeout( “Statements”, milliseconds );

The setTimeout( ) in the JavaScript timing method takes only two parameters:

  • First parameter: This parameter is the statements in the JavaScript language you want to execute. A string function can also be passed as a parameter.
  • Second parameter: This parameter will specify the milliseconds it will take before executing the JavaScript statements mentioned in the first parameter. They can simply be referred to as Delay On Execution.

Structure Of The setTimeout( ) Method

var SetTime = SetTimeout( “SetTimefunction( )”, 500 ); {//code}

Example: To Calculate Milliseconds

To work with the JavaScript event timing methods, it's absolutely important for you to understand how to calculate milliseconds using seconds.

If you have one second ( 1s ) in one thousand milliseconds ( 1000ms )

Milliseconds Formulae

1000ms = 1s Yms = Xs 

if 1000ms = 1s 300ms = Xs 

#cross multiplying 1000ms * Xs = 300ms * 1s X * 1000 = 300 * 1 1000X = 300 X = 300 / 1000 X = 0.3s

This means 300 milliseconds(ms) = 0.3 seconds, not up to one second (1s). Your JavaScript statements will be executed in the time interval of 0.3s.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Creating A Stop Watch

Using the JavaScript timing event methods, we can create our stopwatch.

Example: 

var cl;
function Stop_Watch() { 
  // javascript statement here 
  cl = SetTimeout( “Stop_Watch( )”, 1000 ); 
}

Or

var stopWatch = function ( ) { 
  // javascript statement here 
  clear = setTimeout( “stopWatch( )”, 1000 ); 
} 

Example: JavaScript Code for startwatch.js

// initialize your variables globally
var count = 0;
var ClearTime;
var sec = 0,
    min = 0,
    hrs = 0;
var clearState;
var secss, mins, gethrs;

function Start_Watch() {
    /* check if seconds(sec) is equal to 60 and add a ‘+1’ to minutes, and set seconds to 0 */
    if (sec === 60) {
        sec = 0;
        min = min + 1;
    }
    mins = (min < 10) ? (‘0’ + min + ‘: ‘) : (min + ‘: ‘);
    /* check if minutes(min) is equal to 60 and add a ‘+1’ to hours set minutes to 0 */
    if (min === 60) {
        min = 0;
        hrs = hrs + 1;
    }
    /* Use the javascript tenary operator to format look of hours and add 0 to hours if it is less than 10 */

    gethrs = (hrs < 10) ? (‘0’ + hrs + ‘: ‘) : (hrs + ‘: ‘);
    secss = (sec < 10) ? (‘0’ + sec) : (sec);
    // display the stopwatch storing it in the variable y 
    var y = document.getElementById(“timer”);
    x.innerHTML = ‘Time: ‘+gethrs + mins + secss;

    /* increment the seconds(sec) counter by ‘+1’ */
    sec++;

    /* Then call the setTimeout( ) to keep the stop watch alive ! */
    clearTime = setTimeout(“Start_Watch()”, 1000);
}

function start_Time() {
    /* It will check if seconds, minutes, and hours are equal to
zero and start the stop watch using Start_Watch() function */
    if (sec === 0 && min === 0 && hrs === 0) {
        /* You have to hide the fulltime while the stop watch is running */
        var fulltime = document.getElementById(“fulltime”);
        fulltime.style.display = “none”;
        /* Also hide the start button if the stop watch is running */
        this.style.display = “none”;
        /* We will call the Start_Watch( ) function to execute the stop watch whenever the start_Time( ) will be triggered */
        Start_Watch();
    } // if () } // start_Time() 
    /* To keep the stop watch alive you need to bind the start_Time( ) function to any event type*/
    window.addEventListener(‘load’, function() {
        var start = document.getElementById(“start”);
        start.addEventListener(‘click’, start_Time);
    });
    // startwatch.js end 

The clearTimeout( ) Method

To stop the timer, you have to call in the clearTimeout( ) timing event method. And this work is done most easily by taking just one parameter.

The parameter of this method is The returned ID of the setTimeout( ) method.

Syntax of the clearTimeout() method:

clearTimeout( return ID of setTimeout() );

Note: The setTimeout( ) method always returns a value, and that returned value is pass to the clearTimeout( ) timing method.

The clearTimeout( ) Parameter

var clearTime = setTimeout( “JavaScript Statements”, 100 );

The clearTime variable will have the value returned by the setTimeout( ) timing method, which can be pass to the clearTimeout( parameter) as an ID to reference it –>

clearTimeout( clearTime );

Working

Whenever the clearTimeout( ) timing method is called on a active setTimeout( ) timing method, then the clearTimeout( ) method will stop/pause the execution of the setTimeout( ) method, without destroying its execution entirely.

The setTimeout( ) method is left idle during the period that the clearTimeout( ) timing method is called without affecting the previous execution; when you re-execute the setTimeout( ) method, it will start from the point where its execution was stopped, not starting all over from the beginning.

Just like when you pause an mp3 media player and then play it back, it continues playing from the previous position, but not starting all over from the beginning.

Let's understand the method's working with an example: If I have a running timer created using the setTimeout() method and its starting point are 00 when I run the timer, its reading changes to 41.

If I call in the clearTimeout( ) method on this active setTimout( ) method, it will make the time idle during that period, and whenever I re-execute the setTimeout( ) method, it will start counting from 41 and not from 00.

So if you want to make the timer start from 00, you've to reset its counter. 

Example: Stop The Time – stopwatch.js

//To stop a function create-> Stop_Time( )
{
    /* Next is to check that minutes, seconds, hours are ‘0’ or not. */
    if (sec !== 0 || min !== 0 || hrs !== 0) {
        /* You have to display the full time before the reseting is done*/
        var fulltime = document.getElementById(“FullTime”);
        //display the full time 
        fulltime.style.display = “block”;
        var time = gethrs + mins + secs;
        fulltime.innerHTML = ‘Fulltime: ‘+time;
        // reset the stop watch 
        sec = 0;
        min = 0;
        hrs = 0;
        secs = ‘0’ + sec;
        mins = ‘0’ + min + ‘: ‘;
        gethrs = ‘0’ + hrs + ‘: ‘;
        var x = document.getElementById(“Timer”);
        var stopTime = gethrs + mins + secs;
        x.innerHTML = stopTime;
        /* display all stop watch control buttons */
        var showStart = document.getElementById(‘start’);
        showStart.style.display = “inline - block”;
        var showStop = document.getElementById(“stop”);
        showStop.style.display = “inline - block”;
        /* clear the stop watch using the setTimeout( ) function and return value ‘clearTime’ as ID */
        clearTimeout(clearTime);
    }
    // if () } // stopTime() 
    /* you need to call the Stop_Time( ) function to terminate/end the Stop Watch */
    window.addEventListener(‘load’, function() {
        var stop = document.getElementById(“stop”);
        stop.addEventListener(‘click’, stopTime);
    });

    // stopwatch.js end 

The CSS

#StopWatch {
width: 290px;
height: auto;
text-align: center;
display: block;
padding: 5px;
margin: 0 auto;
}

#timer and #fulltime {
width: auto;
height: auto;
padding: 9px;
font-weight: bold;
font-family: tahoma;
display: block;
border: 2px solid #eee;
text-align: center;
box-shadow: 0 0 4px #ccc;
background: #fbfbf0;
color: darkblue;
border-bottom: 5px solid grey;
}

button {
cursor: pointer;
font-weight: 700;
}

#fulltime {
display: none;
font-size: 16px;
font-weight: bold;
}

The HTML

<!DOCTYPE html>
<html lang=”en”> 
<head>
<title> Stop Watch </title> 
<style text=”text/css”> </style> 
<script type=”text/javascript”> 
</script> 
</head> 
<body> <section id=”Stop_Watch”>
<p id=”timer_start”> Time : 00:00:00 </p> <button id=”start”> Start </button> <button id=”stop”> Stop </button> <p id=”full_time”> </p> 
</section>
</body> 
</html> 

The stopwatch is completed, and this is how it should look.

A small timer with start and stop buttons

Frequently Asked Questions

1. What do you mean by an Event Listener in JavaScript?

It is a procedure in javascript that waits for an event to get triggered. For example, a user clicking the mouse is also an event.

 

2. How a StopWatch is created using different languages?

StopWatch's user interface is being built up with the help of HTML and CSS, and that user interface has been made functional using JavaScript. JavaScript timing methods automate a particular task on the fly without you having to click a button or call an event.

Conclusion

This article has covered the JavaScript project "StopWatch." The stopwatch will start when the user clicks the start button, and it will run every second, displaying the full clock as 00:00:00. Skills needed for this project are HTML, CSS, and JavaScript.

If you are unaware of these skills or have forgotten some of the concepts, then you must visit these articles for each skill for better understanding. HTMLCSS, and JavaScript.

Happy Coding!!!

Previous article
Implement digital watch/Timer in vanilla JS and show time in HH:MM:SS format
Next article
Implement StopWatch in vanilla JS and show time in HH: MM: SS format
Live masterclass