Stopwatch in JS. 10 Days 10 Beginner JS Projects. Day 5

Stopwatch in JS. 10 Days 10 Beginner JS Projects. Day 5

You’ve learned HTML and CSS and started to learn JavaScript. You studied all the basics. Now it is time to practice.

But... What should I build?

We'll build 10 projects in 10 days. We'll be exploring 10 beginner-friendly JavaScript projects one by one that will help you sharpen your skills and get you started on your journey to becoming a skilled web developer. These projects are easy to follow and require minimal experience, making them perfect for beginners. Let's get started and dive into the exciting world of JavaScript projects! We'll focus on JavaScript so I won't explain every HTML and CSS code. You can style it however you want and add things to make your own.

Let's go.

What we will build in 10 days:

  1. Simple Calculator

  2. Random Quote Generator

  3. To-do List

  4. Image Slider

  5. Stopwatch

  6. Weather App with an API

  7. Random Number Guessing Game

  8. Rock-Paper-Scissors

  9. Memory Game

  10. Countdown Timer.

Day 5.

Stopwatch.

Wow, we're already halfway through the '10 Days 10 Beginner JS Projects' challenge.

Today we'll build a simple stopwatch with start, stop and reset buttons.

Let's start with HTML.

We need:

  1. A div to show time(seconds, minutes)

  2. 3 buttons for start, pause, reset

<div id="stopwatch">
  <div id="display">00:00:00</div>
  <div class='buttons'>
    <button id="start">Start</button>
    <button id="stop">Stop</button>
    <button id="reset">Reset</button>
  </div>  
</div>

Simple CSS:

body{
  display:flex;
  justify-content:center;
  align-items:center;
  min-height:100vh;
}

#stopwatch {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 3rem;
  margin-top: 1rem;
}

#display {
  font-weight: bold;
  margin-bottom: 1rem;
}

button {
  font-size: 1.5rem;
  padding: 0.5rem 1rem;
  margin-right: 0.5rem;
  cursor:pointer;
}

And JS part:

const display = document.getElementById("display");
const startBtn = document.getElementById("start");
const stopBtn = document.getElementById("stop");
const resetBtn = document.getElementById("reset");

In this code, we created display, startBtn, stopBtn, and resetBtn variables that are assigned to HTML elements using document.getElementById() method. The const keyword is used to declare variables that cannot be reassigned later.

let startTime;
let elapsedTime = 0;
let timerInterval;

The let keyword is used to declare variables that can be reassigned later. In this code, startTime, elapsedTime, and timerInterval are variables that are declared using let.

function startTimer() {
  startTime = Date.now() - elapsedTime;
  timerInterval = setInterval(() => {
    elapsedTime = Date.now() - startTime;
    updateDisplay();
  }, 10);
}
  • startTime = Date.now() - elapsedTime; This line of code gets the current time using the Date.now() method and subtracts the elapsed time from it. We declared elapsedTime equal to '0' above. This is because we want to start the stopwatch from where it left off if it was previously stopped.

  • timerInterval = setInterval(() => {...}, 10);: This line of code sets up an interval that runs a function every 10 milliseconds. The function inside the interval updates the elapsed time and the display.

  • elapsedTime = Date.now() - startTime;: This line of code calculates the elapsed time by subtracting the startTime from the current time using the Date.now() method.

  • updateDisplay();: This line of code calls the updateDisplay() function to update the stopwatch display with the new elapsed time.

Overall, the startTimer() function sets up an interval that updates the elapsed time and displays every 10 milliseconds, starting from the time when the start button was clicked.

function stopTimer() {
  clearInterval(timerInterval);
}

This line of code stops the interval that was previously set up in the startTimer() function. The timerInterval variable holds a reference to the interval that was created, so calling clearInterval(timerInterval) stops that interval.

function resetTimer() {
  clearInterval(timerInterval);
  elapsedTime = 0;
  updateDisplay();
}
  • clearInterval(timerInterval);This line of code stops the interval that was previously set up in the startTimer() function. The timerInterval variable holds a reference to the interval that was created, so calling clearInterval(timerInterval) stops that interval.

  • elapsedTime = 0;This line of code sets the elapsed time to 0, effectively resetting the stopwatch.

  • updateDisplay();: This line of code calls the updateDisplay() function to update the stopwatch display with the new elapsed time (which is now 0).

The resetTimer() function stops the interval that updates the elapsed time and display, sets the elapsed time to 0, and updates the stopwatch display to show the new elapsed time (which is now 0), effectively resetting the stopwatch to its initial state.

function updateDisplay() {
  const minutes = Math.floor(elapsedTime / 60000);
  const seconds = Math.floor((elapsedTime % 60000) / 1000);
  const milliseconds = elapsedTime % 100;
  display.textContent = `${padNumber(minutes)}:${padNumber(seconds)}:${padNumber(milliseconds, 2)}`;
}
  • const minutes = Math.floor(elapsedTime / 60000);: This line of code calculates the number of minutes that have elapsed by dividing the elapsedTime by 60000 (the number of milliseconds in a minute) and rounding down to the nearest integer using the Math.floor() method.

  • const seconds = Math.floor((elapsedTime % 60000) / 1000);: This line of code calculates the number of seconds that have elapsed by taking the remainder of the elapsedTime divided by 60000 (the number of milliseconds in a minute), then dividing that result by 1000 (the number of milliseconds in a second) and rounding down to the nearest integer using the Math.floor() method.

  • const milliseconds = elapsedTime % 1000;: This line of code calculates the number of milliseconds that have elapsed by taking the remainder of the elapsedTime divided by 1000 (the number of milliseconds in a second).

  • display.textContent=${padNumber(minutes)}:${padNumber(seconds)}:${padNumber(milliseconds, 3)};: This line of code sets the text content of the display element to a formatted string that shows the elapsed time in minutes, seconds, and milliseconds. The padNumber() function is used to add leading zeros to the numbers so that they all have two digits (for minutes and seconds) or three digits (for milliseconds).

The updateDisplay() function calculates the elapsed time in minutes, seconds, and milliseconds, formats it as a string, and updates the stopwatch display with the new elapsed time.

function padNumber(number, length = 2) {
  return number.toString().padStart(length, "0");
}
  • number.toString() converts the number argument to a string so that we can manipulate it as a string.

  • .padStart(length, "0")uses the padStart() method to add leading zeros to the string so that it is length characters long. The second argument ("0") specifies that we want to pad the string with zeros.

  • length = 2sets a default value of 2 for the length parameter. This means that if the length argument is not passed to the function, it will default to 2.

    The padNumber() function takes a number and pads it with leading zeros so that it has length digits. This is useful for formatting the minutes, seconds, and milliseconds in the stopwatch display so that they always have two digits (for minutes and seconds) or three digits (for milliseconds), regardless of their actual value.

startBtn.addEventListener("click", startTimer);
stopBtn.addEventListener("click", stopTimer);
resetBtn.addEventListener("click", resetTimer);

Finally, we use the addEventListener() method to add event listeners to buttons. startTimer(), stopTimer(), and resetTimer() functions are called when the start, stop, and reset buttons are clicked.

Here is the full JS code.

const display = document.getElementById("display");
const startBtn = document.getElementById("start");
const stopBtn = document.getElementById("stop");
const resetBtn = document.getElementById("reset");

let startTime;
let elapsedTime = 0;
let timerInterval;

function startTimer() {
  startTime = Date.now() - elapsedTime;
  timerInterval = setInterval(() => {
    elapsedTime = Date.now() - startTime;
    updateDisplay();
  }, 10);
}

function stopTimer() {
  clearInterval(timerInterval);
}

function resetTimer() {
  clearInterval(timerInterval);
  elapsedTime = 0;
  updateDisplay();
}

function updateDisplay() {
  const minutes = Math.floor(elapsedTime / 60000);
  const seconds = Math.floor((elapsedTime % 60000) / 1000);
  const milliseconds = elapsedTime % 100;
  display.textContent = `${padNumber(minutes)}:${padNumber(seconds)}:${padNumber(milliseconds, 2)}`;
}

function padNumber(number, length = 2) {
  return number.toString().padStart(length, "0");
}

startBtn.addEventListener("click", startTimer);
stopBtn.addEventListener("click", stopTimer);
resetBtn.addEventListener("click", resetTimer);

That is for today. Hope you like it.

See you tomorrow.

Here is the GitHub code.