How to create a stopwatch using JavaScript?

Learn how to create a stopwatch using javascript? with practical examples, diagrams, and best practices. Covers javascript, jquery development techniques with visual explanations.

Build a Simple Stopwatch with JavaScript

Hero image for How to create a stopwatch using JavaScript?

Learn how to create a functional stopwatch using HTML, CSS, and vanilla JavaScript, covering core logic for timing, display updates, and control buttons.

Creating a stopwatch is a classic and practical project for anyone learning JavaScript. It involves managing time, updating the user interface dynamically, and handling user interactions. This article will guide you through building a fully functional stopwatch from scratch, explaining each component and the underlying logic.

Understanding the Core Stopwatch Logic

At its heart, a stopwatch needs to track elapsed time and update a display. We'll use JavaScript's setInterval() function to repeatedly execute a piece of code, incrementing our time counter. The time will be stored in milliseconds, then converted into minutes, seconds, and milliseconds for display. User actions like 'Start', 'Stop', and 'Reset' will control this timing mechanism.

flowchart TD
    A[User Clicks Start] --> B{Is Timer Running?}
    B -- No --> C[Initialize Time Variables]
    C --> D[Start setInterval()]
    D --> E[Increment Milliseconds]
    E --> F[Update Display]
    F --> G{1000ms Reached?}
    G -- Yes --> H[Increment Seconds]
    H --> I{60s Reached?}
    I -- Yes --> J[Increment Minutes]
    J --> K[Reset Seconds to 0]
    K --> L[Reset Milliseconds to 0]
    L --> F
    I -- No --> L
    G -- No --> F
    B -- Yes --> M[Do Nothing]
    N[User Clicks Stop] --> O[Clear setInterval()]
    P[User Clicks Reset] --> Q[Clear setInterval()]
    Q --> R[Reset All Time Variables to 0]
    R --> S[Update Display to 00:00:00]
    O --> T[Stopwatch Stopped]
    S --> T

Flowchart illustrating the core logic of a JavaScript stopwatch.

Setting Up the HTML Structure

First, we need a basic HTML structure to display the stopwatch and provide control buttons. We'll use div elements for the display and button elements for 'Start', 'Stop', and 'Reset'. Each element will have a unique ID to allow easy manipulation with JavaScript.

<div class="stopwatch-container">
    <div id="display" class="time-display">00:00:00</div>
    <div class="controls">
        <button id="startBtn">Start</button>
        <button id="stopBtn">Stop</button>
        <button id="resetBtn">Reset</button>
    </div>
</div>

Basic HTML structure for the stopwatch.

While not strictly necessary for functionality, adding some CSS will make our stopwatch visually appealing and easier to use. Here's a simple stylesheet to get you started.

.stopwatch-container {
    font-family: 'Arial', sans-serif;
    text-align: center;
    margin-top: 50px;
    background-color: #222;
    color: #0f0;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 15px rgba(0, 255, 0, 0.5);
    width: 300px;
    margin-left: auto;
    margin-right: auto;
}

.time-display {
    font-size: 3em;
    margin-bottom: 20px;
    letter-spacing: 3px;
}

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

#startBtn {
    background-color: #4CAF50;
    color: white;
}

#startBtn:hover {
    background-color: #45a049;
}

#stopBtn {
    background-color: #f44336;
    color: white;
}

#stopBtn:hover {
    background-color: #da190b;
}

#resetBtn {
    background-color: #008CBA;
    color: white;
}

#resetBtn:hover {
    background-color: #007bb5;
}

Basic CSS for styling the stopwatch.

Implementing the JavaScript Logic

Now for the core functionality. We'll need variables to keep track of the time (milliseconds, seconds, minutes), a variable to hold our setInterval ID, and a boolean to indicate if the stopwatch is running. Event listeners will be attached to the buttons to trigger the start, stop, and reset functions.

let milliseconds = 0;
let seconds = 0;
let minutes = 0;
let timer;
let isRunning = false;

const display = document.getElementById('display');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const resetBtn = document.getElementById('resetBtn');

function formatTime(unit) {
    return unit < 10 ? '0' + unit : unit;
}

function updateDisplay() {
    const formattedMinutes = formatTime(minutes);
    const formattedSeconds = formatTime(seconds);
    const formattedMilliseconds = formatTime(Math.floor(milliseconds / 10)); // Displaying hundredths
    display.textContent = `${formattedMinutes}:${formattedSeconds}:${formattedMilliseconds}`;
}

function startTimer() {
    if (!isRunning) {
        isRunning = true;
        timer = setInterval(() => {
            milliseconds += 10; // Increment by 10ms for smoother hundredths display
            if (milliseconds === 1000) {
                milliseconds = 0;
                seconds++;
                if (seconds === 60) {
                    seconds = 0;
                    minutes++;
                }
            }
            updateDisplay();
        }, 10); // Update every 10 milliseconds
    }
}

function stopTimer() {
    if (isRunning) {
        isRunning = false;
        clearInterval(timer);
    }
}

function resetTimer() {
    stopTimer(); // Stop if running
    milliseconds = 0;
    seconds = 0;
    minutes = 0;
    updateDisplay();
}

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

JavaScript code for stopwatch functionality.

Integrating jQuery (Optional)

If you're already using jQuery in your project, you can simplify the DOM manipulation and event handling. Here's how you might adapt the JavaScript code to use jQuery.

Vanilla JavaScript

const display = document.getElementById('display'); const startBtn = document.getElementById('startBtn'); const stopBtn = document.getElementById('stopBtn'); const resetBtn = document.getElementById('resetBtn');

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

jQuery

$(document).ready(function() { const $display = $('#display'); const $startBtn = $('#startBtn'); const $stopBtn = $('#stopBtn'); const $resetBtn = $('#resetBtn');

// ... (rest of the timer logic remains the same)

$startBtn.on('click', startTimer);
$stopBtn.on('click', stopTimer);
$resetBtn.on('click', resetTimer);

function updateDisplay() {
    const formattedMinutes = formatTime(minutes);
    const formattedSeconds = formatTime(seconds);
    const formattedMilliseconds = formatTime(Math.floor(milliseconds / 10));
    $display.text(`${formattedMinutes}:${formattedSeconds}:${formattedMilliseconds}`);
}

});

The core logic for startTimer, stopTimer, resetTimer, updateDisplay, and formatTime functions remains largely the same, as they deal with pure JavaScript logic and not directly with DOM manipulation. jQuery primarily simplifies selecting elements and attaching event listeners.