A stopwatch is a useful tool to measure the time accurately. For example, we can keep track of the time during sports events, cooking competitions, or while performing any scientific experiments. It has always been convenient to use a stopwatch but, over the period of time, it has become even more accessible with the emergence of modern world software and web applications.
In this Answer, we’ll build a stopwatch, step by step, using JavaScript and HTML. To handle the functionality of the stopwatch, we’ll start by using the JavaScript object Date()
, to keep track of time, and the method setInterval()
, to update the stopwatch display at regular intervals. To handle the
We have written a simple HTML code to display a stopwatch on a web page. The HTML code includes a <div>
element with an attribute id
set to the stopwatch, which will display the current time. Then, we have created three buttons, “Start”, “Stop”, and “Reset”, using the <button>
element. These buttons will be used to control the stopwatch.
Let’s look at some of the JavaScript functions we have used to handle the functionality of the stopwatch.
The function startStopwatch()
gets the current time in milliseconds using new Date().getTime()
, and starts an interval using setInterval()
to update the stopwatch display every second. Inside startStopwatch()
, we first calculate and save the start time in the variable startTime
. The start time is the difference between the current time and the elapsedPausedTime
. This is important because the elapsedPausedTime
variable keeps track of the total time for which the stopwatch has been paused, and subtracting it from the current time ensures that the timer resumes from the correct position, even if the user clicks the “Start” button after clicking the “Stop” button. Next, we update the time being displayed on the web page using the function setInterval()
.
Now that we have added the functionality of the “Start” button, let’s proceed toward the functionality of the “Stop” button.
The function stopStopwatch()
stops the interval using clearInterval()
. It also calculates the elapsedPausedTime
by subtracting the startTime
(when the stopwatch was initially started) from the current time. This ensures that the stopwatch resumes from the correct position, instead of resetting to when the startStopwatch()
function is called after the stopwatch has been paused.
The function resetStopwatch()
stops the interval using stopStopwatch()
, resets the elapsedPausedTime
to , and displays “” on the screen.
The function updateStopwatch()
calculates the elapsed time in milliseconds starting from the start time. It converts it to hours, minutes, and seconds, formats the display time as , and updates the stopwatch element’s innerHTML.
We’ll also use the function pad()
to add a leading to a number if it’s less than to ensure that the display time always has two digits for hours, minutes, and seconds.
That's it! We're done with creating a stopwatch.
Free Resources