Creating a simple stopwatch with JavaScript

A stopwatch is a timepiece that allows you to measure the amount of time elapsed between two points in time. In this article, we’ll show you how to create a simple stopwatch using JavaScript that can be used to time events or measure the execution time of a block of code.

Demo Application

Output - Creating a simple stopwatch with JavaScript - Clue Mediator
Output – Creating a simple stopwatch with JavaScript – Clue Mediator

HTML and CSS

The first step is to create the HTML and CSS for the stopwatch. We’ll create a simple layout consisting of a display area for the stopwatch, and three buttons for start, stop, and reset.

The CSS for the stopwatch is also simple, with some basic styling applied to the display area and the buttons.

JavaScript

Now, we can start with the JavaScript code for the stopwatch. We’ll use the setInterval function to increment the stopwatch display every millisecond. We’ll also use a state object to keep track of the stopwatch state.

Let’s go through the code step by step.

We first declare a state object to keep track of the stopwatch state. The running property keeps track of whether the stopwatch is currently running, the elapsed property keeps track of the elapsed time, and the intervalId property holds the ID of the interval returned by the setInterval function.

The update function is responsible for updating the stopwatch display. It calculates the minutes, seconds, and milliseconds from the elapsed time and updates the display with the padded values.

The pad function is a utility function that pads a number with a leading zero if it is less than 10.

The start function starts the stopwatch by setting up an interval that increments the elapsed time every 10 milliseconds. It also sets the running property to true.

Let’s combine all code together and see how it looks.

index.html

Conclusion

In this article, we explained to you how to create a simple stopwatch with JavaScript. We started with the basics of JavaScript, created the HTML structure, and implemented the JavaScript code.

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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