Create a simple stopwatch in JavaScript with Start, Stop and Pause functionality

Create a simple stopwatch in JavaScript with Start, Stop and Pause functionality

JavaScript stop watch can be developed using the JavaScript timing methods which are executed in time intervals.

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

JavaScript timing is made up of two key methods:

setTimeout( “function”, milliseconds );
clearTimeout( ID name of setTimeout( ) );

How to create stop watch from start:

Lets start creating stopwatch using javascript. We will create two files stopwatch.html and stopwatch.js for this example. In stopwatch.html copy below html code and save in your drive.

<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
<title>Clock</title>
<script src=”stopwatch.js”></script>
</head>
<body>
<main>
<h1>Digital Stopwatch</h1>

<fieldset>
<legend>Stop Watch</legend>
<a href=”#” id=”startwatch”>Start</a>&nbsp;
<a href=”#” id=”stopwatch”>Stop</a>&nbsp;
<a href=”#” id=”resetwatch”>Reset</a>&nbsp;
<span id=”minutes”>00</span>:
<span id=”seconds”>00</span>:
<span id=”ms”>000</span>
</fieldset>
</main>
</body>
</html>

In this html code we are calling stopwatch.js under <script> tag which will include all the functionality of stopwatch.

Below that is fieldset area and we will display the watch under three span with id “minutes” for minute, “seconds” for second, and “ms” for millisecond. We will also use three links to start, stop and reset the stop watch. Start and stop links function can further be modified to create laps, however in this example we are going to use this to stop and start the stopwatch.


Now create file stopwatch.js and put below code in this. In this code we are creating three variables minutes, seconds and milliseconds which will help us to display the stopwatch time inside html span code.

You will notice var stopwatch Timer also initialized on top of code. This is very helpful in creating stop and pause functionality of timer.

After initializing the variable create a function “singleDigit” with if condition we are going to use this function as our digitial watch to display two digit value of second between 0 – 10.

Now we need to create the main function which will display the time on span. To do that create a function “stopwatch” as below. Here we will increase the millisecond variable by 10 millisecond each time script will run this function. Each time once millisecond will reach 1000 i.e 1 second it will increase elapsedSeconds variable by 1 sec. And if elapsedSeconds will reach 60 it will increase the value of elapsedMinutes by 1 minute and reset the elapsedSeconds to 0. This function is main base of stopwatch and all the login of working functionality this. Once millisecond reach 1000 it will reset to 0 and increase the second to +1 and once seconds reach 60 it will reset to 0 and increase the minute to +1.

Now we will display the result of our function on html span tag using “firstChild.nodeValue “. You can also use .innerHTML tag to display the value inside span tag.

//global stop watch timer variable and elapsed time object
var stopwatchTimer;
var elapsedMinutes = 0;
var elapsedSeconds = 0;
var elapsedMilliseconds = 0;

var singleDigit = function(num) {

if (num < 10) { return “0” + num; }
else { return num; }

};

var stopwatch = function() {
// increment milliseconds by 10 milliseconds
elapsedMilliseconds +=10;

if(elapsedMilliseconds==1000){
elapsedSeconds += 1;
elapsedMilliseconds = 0;
}
// if milliseconds total 1000, increment seconds by one and reset milliseconds to zero

if(elapsedSeconds==60){
elapsedMinutes += 1;
elapsedSeconds = 0;
}
// if seconds total 60, increment minutes by one and reset seconds to zero

//display new stopwatch time

$(“s_minutes”).firstChild.nodeValue = singleDigit(elapsedMinutes);
$(“s_seconds”).firstChild.nodeValue = singleDigit(elapsedSeconds);
$(“s_ms”).firstChild.nodeValue = elapsedMilliseconds;

};

Now to start the stop watch we need to call this function on click of start link. For this we will use onclick method of JavaScript. Put below code to call the function here we are calling three function startStopwatch, stopStopwatch and resetStopwatch to perform the respective functionality. We will initialize onclick function on window page load.
window.onload = function() {
// set up stopwatch event handlers
$(“startwatch”).onclick = startStopwatch;
$(“stopwatch”).onclick = stopStopwatch;
$(“resetwatch”).onclick = resetStopwatch;

};

Now lets understand the startStopwatch function. We will use this function to start the stopwatch. Here we are preventing by default functionality of href as we need to call function. After that we will initialize stopwatchTimer variable and call the stopwatch function with 10 millisecond interval. So stopwatch function which we have created above will run after every 10 milliseconds.

// event handler functions
var startStopwatch = function(evt) {

// prevent default action of link

evt.preventDefault();

// do first tick of stop watch and then set interval timer to tick
// stop watch every 10 milliseconds. Store timer object in stopwatchTimer
// variable so next two functions can stop timer.

stopwatchTimer = setInterval(stopwatch, 10);

};
Now as watch is running we also need to stop and pause that. For same we call simple clearInterval function of JavaScript as below.

var stopStopwatch = function(evt) {

// prevent default action of link

evt.preventDefault();

// stop timer

clearInterval(stopwatchTimer);

};
For reset function we need to clear the Interval and also need to set default variables to 0 once again.

var resetStopwatch = function(evt) {

// prevent default action of link
evt.preventDefault();

// stop timer
clearInterval(stopwatchTimer);

// reset elapsed variables and clear stopwatch display
$(“s_ms”).firstChild.nodeValue = “000”;
$(“s_seconds”).firstChild.nodeValue = “00”;
$(“s_minutes”).firstChild.nodeValue = “00”;

elapsedMilliseconds = 0;
elapsedMinutes = 0;
elapsedSeconds = 0;

};

Now your stopwatch in JavaScript is ready to go. Below if stopwatch.js complete functionality once again.
“use strict”;
var $ = function(id) { return document.getElementById(id); };

var evt = {

attach: function(node, eventName, func) {

},

detach: function(node, eventName, func) {

},

preventDefault: function(e) {

}
};

//global stop watch timer variable and elapsed time object
var stopwatchTimer;
var elapsedMinutes = 0;
var elapsedSeconds = 0;
var elapsedMilliseconds = 0;

var singleDigit = function(num) {

if (num < 10) { return “0” + num; }
else { return num; }

};

var stopwatch = function() {
// increment milliseconds by 10 milliseconds
elapsedMilliseconds +=10;

if(elapsedMilliseconds==1000){
elapsedSeconds += 1;
elapsedMilliseconds = 0;
}
// if milliseconds total 1000, increment seconds by one and reset milliseconds to zero

if(elapsedSeconds==60){
elapsedMinutes += 1;
elapsedSeconds = 0;
}
// if seconds total 60, increment minutes by one and reset seconds to zero

//display new stopwatch time

$(“s_minutes”).firstChild.nodeValue = singleDigit(elapsedMinutes);
$(“s_seconds”).firstChild.nodeValue = singleDigit(elapsedSeconds);
$(“s_ms”).firstChild.nodeValue = elapsedMilliseconds;

};

// event handler functions
var startStopwatch = function(evt) {

// prevent default action of link

evt.preventDefault();

// do first tick of stop watch and then set interval timer to tick
// stop watch every 10 milliseconds. Store timer object in stopwatchTimer
// variable so next two functions can stop timer.

stopwatchTimer = setInterval(stopwatch, 10);

};

var stopStopwatch = function(evt) {

// prevent default action of link

evt.preventDefault();

// stop timer

clearInterval(stopwatchTimer);

};

var resetStopwatch = function(evt) {

// prevent default action of link
evt.preventDefault();

// stop timer
clearInterval(stopwatchTimer);

// reset elapsed variables and clear stopwatch display
$(“s_ms”).firstChild.nodeValue = “000”;
$(“s_seconds”).firstChild.nodeValue = “00”;
$(“s_minutes”).firstChild.nodeValue = “00”;

elapsedMilliseconds = 0;
elapsedMinutes = 0;
elapsedSeconds = 0;

};

window.onload = function() {

// set initial clock display and then set interval timer to display
// new time every second. Don’t store timer object because it
// won’t be needed – clock will just run.
displayCurrentTime();
setInterval(displayCurrentTime, 1000);

// set up stopwatch event handlers
$(“startwatch”).onclick = startStopwatch;
$(“stopwatch”).onclick = stopStopwatch;
$(“resetwatch”).onclick = resetStopwatch;

};

 

Share this post

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.