How to Create a Stopwatch in JavaScript

How to Create a Stopwatch in JavaScript

JavaScript stop watch or rather stop down timer 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.

JavaScript timing is made up of two key methods:

  • setTimeout( “javascript expression”, milliseconds );
  • clearTimeout( ID of setTimeout( ) );

When using the JavaScript timing methods, you need to understand how JavaScript executes statements in time intervals.

The setTimeout( ) Method

Syntax:

setTimeout( "JavaScript Statements", milliseconds );

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

  • first parameter: this parameter is the JavaScript statements you want to execute. A string function name can also be passed to it.
  • second parameter: specifies the milliseconds it is going to take before executing the JavaScript statements in the first parameter. It can simply be referred to as ( Delay On Execution ).

Example : Structure Of The setTimeout( ) Method

var setTime = setTimeout( function ( ) {
// javascript statements }, 500 ); Or var setTime = setTimeout( "setTimeFunction( )", 500 ); 

Example: Calculating Milliseconds

To work with the JavaScript event timing methods, it’s very important you understand how to calculate milliseconds.

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 = 0.3 seconds, not up to one second (1s). Your JavaScript statements will be executed in time interval of 0.3 seconds (0.3s).

Creating A Stop Watch

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

Example: The Structure

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

Example: JavaScript Code for startwatch.js

// initialize your variables outside the function var count = 0; var clearTime; var seconds = 0, minutes = 0, hours = 0; var clearState; var secs, mins, gethours ; function startWatch( ) { /* check if seconds is equal to 60 and add a +1 to minutes, and set seconds to 0 */ if ( seconds === 60 ) { seconds = 0; minutes = minutes + 1; } /* you use the javascript tenary operator to format how the minutes should look and add 0 to minutes if less than 10 */ mins = ( minutes < 10 ) ? ( '0' + minutes + ': ' ) : ( minutes + ': ' ); /* check if minutes is equal to 60 and add a +1 to hours set minutes to 0 */ if ( minutes === 60 ) { minutes = 0; hours = hours + 1; } /* you use the javascript tenary operator to format how the hours should look and add 0 to hours if less than 10 */ gethours = ( hours < 10 ) ? ( '0' + hours + ': ' ) : ( hours + ': ' ); secs = ( seconds < 10 ) ? ( '0' + seconds ) : ( seconds ); // display the stopwatch var x = document .getElementById("timer"); x.innerHTML = 'Time: ' + gethours + mins + secs; /* call the seconds counter after displaying the stop watch and increment seconds by +1 to keep it counting */ seconds++; /* call the setTimeout( ) to keep the stop watch alive ! */ clearTime = setTimeout( "startWatch( )", 1000 ); } // startWatch( ) //create a function to start the stop watch
function startTime( ) { /* check if seconds, minutes, and hours are equal to zero and start the stop watch */
if ( seconds === 0 && minutes === 0 && hours === 0 ) { /* hide the fulltime when the stop watch is running */ var fulltime = document.getElementById( "fulltime" ); fulltime.style.display = "none"; /* hide the start button if the stop watch is running */ this.style.display = "none"; /* call the startWatch( ) function to execute the stop watch whenever the startTime( ) is triggered */ startWatch( ); } // if () } // startTime() /* you need to bind the startTime( ) function to any event type to keep the stop watch alive ! */ window.addEventListener( 'load', function ( ) { var start = document .getElementById("start"); start.addEventListener( 'click', startTime ); }); // startwatch.js end

The clearTimeout( ) Method

To stop the timer, you need to call in the clearTimeout( ) timing event method and this comes in very handy.

It has just one parameter : the return ID of the setTimeout( ) method

Syntax:

clearTimeout( return ID of setTimeout() );

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

The ClearTimeout( ) Parameter

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

clearTime variable is returned as a value by the setTimeout( ) timing method, which can be pass to the clearTimeout( ID ) as an ID to reference it –
clearTimeout( clearTime );

How It Works

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

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

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

For example, let’s say I have a running timer that was created using the setTimeout( ) timing method, and its starting point is 00. I run the timer, and it’s now reading 41.

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

To make the timer start from 00, you’ve to resets its counter. That’s the logic.

Example: Stop The Time – stopwatch.js

//create a function to stop the time function stopTime( ) { /* check if seconds, minutes and hours are not equal to 0 */ if ( seconds !== 0 || minutes !== 0 || hours !== 0 ) { /* display the full time before reseting the stop watch */ var fulltime = document .getElementById( "fulltime" ); //display the full time fulltime.style.display = "block"; var time = gethours + mins + secs; fulltime.innerHTML = 'Fulltime: ' + time; // reset the stop watch seconds = 0; minutes = 0; hours = 0; secs = '0' + seconds; mins = '0' + minutes + ': '; gethours = '0' + hours + ': '; /* display the stopwatch after it's been stopped */ var x = document.getElementById ("timer"); var stopTime = gethours + 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( ) return value 'clearTime' as ID */ clearTimeout( clearTime ); } // if () } // stopTime() /* you need to call the stopTime( ) function to terminate the stop watch */ window.addEventListener( 'load', function ( ) { var stop = document.getElementById ("stop"); stop.addEventListener( 'click', stopTime ); }); // stopwatch.js end

The CSS

#stopWatch { width: 280px; height: auto; text-align: center; display: block; padding: 5px; margin: 0 auto; } #timer, #fulltime { width: auto; height: auto; padding: 10px; font-weight: bold; font-family: tahoma; display: block; border: 1px solid #eee; text-align: center; box-shadow: 0 0 5px #ccc; background: #fbfbf0; color: darkblue; border-bottom:4px solid darkgrey; } button { cursor: pointer; font-weight: 700; } #fulltime { display:none; font-size:16px; font-weight:bold; } 

The HTML

<!DOCTYPE html> <html lang="en"> <head> <title> JavaScript Stop Watch </title> <style text="text/css"> </style> <script type="text/javascript"> </script> </head> <body> <section id="stopWatch"> <p id="timer"> Time : 00:00:00 </p> <button id="start"> Start </button> <button id="stop"> Stop </button> <p id="fulltime"> </p> </section> </body> </html> 

The stop watch is completed, and this is how it should look.

A small timer with start and stop buttons

Author

0 0 votes
Article Rating
Subscribe
Notify of
guest

13 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Max_Max
Max_Max
7 years ago

cool

ProsaicHacker
ProsaicHacker
6 years ago

I need a single page browser stopwatch and no external dependencies. this looked promising.

For us mere mortals to whom building a page is a rare and therefore new experience each time, could you have a single page version of the final product. Cutting and pasting the piece together I had to add closing braces for both “start” and “stop” functions to get the console to stop complaining. No yet sure if it was my mistake or yours. Also the buttons do not work I do not know why.

Joe Hawthorn
Joe Hawthorn
4 years ago
Reply to  ProsaicHacker

Please see [url=https://github.com/PieterT2000/stopwatch.js]stopwatch.js[/url] for a clean vanilla JS solution.

Kalalakshmi
Kalalakshmi
4 years ago




Page Title




indraraj
indraraj
4 years ago
Reply to  Kalalakshmi

how can we stop it .Can you reply with code

Meera
Meera
4 years ago
Reply to  Kalalakshmi

How can we stop it ? and how we can start it?
Can we Provide button with a timer class?
I already tried?

meeta
meeta
4 years ago
Reply to  Kalalakshmi

how to stop the timerr

vaishnavi
vaishnavi
3 years ago
Reply to  Kalalakshmi

can plz include how to stop it and restart again

Reconnecting...
Reconnecting...
4 years ago

It doesn’t work…???

Anshika
Anshika
3 years ago

Hey there, I m not from the team but I can give you the codes for a wonderful gold stop watch which is not really available on google chrome, just follow my steps
1. Copy the code given below (from )
2. Paste it on notepad.exe
3. Now save the file with the name, watch.html, with unicode format

CODE:

 
 

  CodePen – Gold Stopwatch
 
 
 
 

 

 
 
 


 

 
   
   
    Gold Stopwatch
       
   
 

 
   

     

GOLD STOPWATCH

     

        00:00:00
     

     

       

       
     

   

   
 

   

 
 
     

 

 

I hope it works for yall…

vaishnavi
vaishnavi
3 years ago
Reply to  Anshika

thanku

Shridhar Upadhyay
Shridhar Upadhyay
3 years ago




   
   
    clock projecet
   
   



   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

   


13
0
Would love your thoughts, please comment.x
()
x