Building a Simple Stopwatch Using JavaScript

Let’s build a simple stopwatch together using JavaScript! In this tutorial, we’ll create a basic web-based stopwatch from scratch. We’ll cover the HTML structure, apply some CSS for styling, and then write JavaScript to bring the stopwatch to life. Follow along, and feel free to experiment as we go.


What You’ll Need

Before we start coding, here’s a quick checklist of what we’ll use:

  • HTML: For creating the structure of the stopwatch.
  • CSS: To style our stopwatch and make it look nice.
  • JavaScript: To add functionality like starting, stopping, and resetting the timer.

You can use any text editor and a web browser to see your progress.


Step 1: Setting Up the HTML

We begin by creating a simple HTML file. This file will contain a display for the time and two buttons: one to start/stop the stopwatch and another to reset it.

Create a file named index.html and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Simple JavaScript Stopwatch</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="stopwatch">
    <h1 id="display">00:00:00</h1>
    <div class="controls">
      <button id="startStop">Start</button>
      <button id="reset">Reset</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>

Here, we have a display area to show the time and two buttons that we’ll hook up with JavaScript later.


Step 2: Adding Some Style with CSS

Next, let’s create a file named styles.css to make our stopwatch look appealing. We’ll center the stopwatch on the page and style the buttons.

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background-color: #f4f4f4;
  font-family: Arial, sans-serif;
}

.stopwatch {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  text-align: center;
}

#display {
  font-size: 3em;
  margin-bottom: 20px;
}

.controls button {
  padding: 10px 20px;
  margin: 0 10px;
  font-size: 1em;
  cursor: pointer;
  border: none;
  border-radius: 5px;
  background-color: #3498db;
  color: #fff;
  transition: background-color 0.3s ease;
}

.controls button:hover {
  background-color: #2980b9;
}

This CSS uses Flexbox to center our stopwatch and applies a clean, modern style to the elements.


Step 3: Making It Work with JavaScript

Now comes the fun part—coding the functionality with JavaScript. We’ll write a script that can start, stop, and reset the stopwatch. Create a file named script.js and add the following code:

let startTime;
let elapsedTime = 0;
let timerInterval;
const display = document.getElementById('display');
const startStopButton = document.getElementById('startStop');
const resetButton = document.getElementById('reset');

// Function to format time as HH:MM:SS
function formatTime(time) {
  const hours = Math.floor(time / (1000 * 60 * 60));
  const minutes = Math.floor((time / (1000 * 60)) % 60);
  const seconds = Math.floor((time / 1000) % 60);

  const formattedHours = hours < 10 ? `0${hours}` : hours;
  const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;
  const formattedSeconds = seconds < 10 ? `0${seconds}` : seconds;

  return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}

// Start the stopwatch
function startStopwatch() {
  startTime = Date.now() - elapsedTime;
  timerInterval = setInterval(() => {
    elapsedTime = Date.now() - startTime;
    display.textContent = formatTime(elapsedTime);
  }, 10);
  startStopButton.textContent = 'Stop';
}

// Stop the stopwatch
function stopStopwatch() {
  clearInterval(timerInterval);
  startStopButton.textContent = 'Start';
}

// Toggle start and stop on button click
startStopButton.addEventListener('click', () => {
  if (startStopButton.textContent === 'Start') {
    startStopwatch();
  } else {
    stopStopwatch();
  }
});

// Reset the stopwatch
resetButton.addEventListener('click', () => {
  stopStopwatch();
  elapsedTime = 0;
  display.textContent = "00:00:00";
});

How It Works:

  • Variables and Elements:
    We initialize variables to keep track of time and get references to our display and buttons.
  • Formatting Time:
    The formatTime function converts the elapsed milliseconds into a human-readable format (hours:minutes:seconds).
  • Starting the Stopwatch:
    The startStopwatch function sets the start time and uses setInterval to update the display every 10 milliseconds.
  • Stopping the Stopwatch:
    The stopStopwatch function stops the interval, effectively pausing the stopwatch.
  • Event Listeners:
    We attach event listeners to the buttons to handle starting, stopping, and resetting the stopwatch.

Final Thoughts

And that’s it! Together, we’ve built a simple yet functional stopwatch using HTML, CSS, and JavaScript. Feel free to expand on this project—maybe add milliseconds to the display, include a lap feature, or enhance the styling further.

I hope you enjoyed building this project with me. Happy coding, and let’s keep exploring new ways to create and innovate with JavaScript!

Leave a Comment

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

Scroll to Top