How to make a stopwatch on JavaScript

This article explains how to create a stopwatch using JavaScript, with code snippets to get you started.

Creating a Stopwatch using JavaScript

A stopwatch is a device used to measure time interval, and it can be created using JavaScript. We will use the Date object to measure the time interval and the setInterval() method to call a function every second.

Step 1: Creating the HTML

First, we need to create a basic HTML page with a div to contain the stopwatch.


<html>
  <head>
    <title>Stopwatch</title>
  </head>
  <body>
    <h1>Stopwatch</h1>
    <div id="stopwatch"></div>
  </body>
</html>

Step 2: Creating the JavaScript

Now, we will create the JavaScript. We will create a function that will be called every second to update the stopwatch.


// Get the stopwatch div
let stopwatch = document.getElementById("stopwatch");

// Get the starting time
let startTime;

// Get the difference between the starting time and the current time
let diff;

// Set the current time to 0
let currentTime = 0;

// Create a function to update the stopwatch
function updateTime() {
  // Get the current time
  let currentTime = new Date().getTime();
  // Calculate the time difference
  diff = currentTime - startTime;
  // Calculate the seconds, minutes and hours
  let hours = Math.floor(diff / (1000 * 60 * 60));
  let minutes = Math.floor(diff / (1000 * 60)) % 60;
  let seconds = Math.floor(diff / 1000) % 60;
  // Format the output
  let output = hours + ":" + minutes + ":" + seconds;
  // Update the stopwatch div
  stopwatch.innerHTML = output;
}

// Create a function to start the stopwatch
function start() {
  // Set the starting time
  startTime = new Date().getTime();
  // Call the updateTime() function every second
  setInterval(updateTime, 1000);
}

Step 3: Calling the start() function

Finally, we need to call the start() function when the page is loaded. We can do this using the window.onload event.


// Call the start() function when the page is loaded
window.onload = start;

And that's it! We have now created a basic stopwatch using JavaScript.

Answers (0)