41 - Stopwatch app that tracks elapsed time

Description

Develop a React component that functions as a stopwatch, tracking elapsed time and providing start/stop controls.

  • Visually displays the elapsed time in a clear format (minutes, seconds, milliseconds).

  • Offers start, stop, and reset buttons.

  • Continues to count time even when the browser tab is inactive.

  • Optionally supports features like:

    • Lap times

    • Countdown timer mode

    • Sound alerts

Algorithm

  1. Component Structure:

    • Define a functional component named Stopwatch.

    • Maintain internal state for:

      • isRunning: Boolean indicating if the stopwatch is active.

      • elapsedTime: Number storing the elapsed time in milliseconds.

      • intervalId: Reference to the interval timer for updates.

      • Optionally: lapTimes: Array to store lap times.

  2. Time Tracking:

    • Use setInterval to create an interval that updates the elapsedTime state every millisecond when the stopwatch is running.

    • Calculate and display the elapsed time in a readable format (minutes, seconds, milliseconds).

  3. Start/Stop Buttons:

    • Implement startStopwatch and stopStopwatch functions:

      • startStopwatch: Sets isRunning to true, starts the interval timer, and stores the start time.

      • stopStopwatch: Clears the interval timer (clearInterval), sets isRunning to false, and optionally records a lap time.

  4. Reset Button:

    • Implement a resetStopwatch function to clear the elapsedTime state and stop the timer if running.

Code

import React, { useState, useEffect } from 'react';

const Stopwatch = () => {
  const [isRunning, setIsRunning] = useState(false);
  const [elapsedTime, setElapsedTime] = useState(0);
  const [intervalId, setIntervalId] = useState(null);
  const [lapTimes, setLapTimes] = useState([]);

  useEffect(() => {
    let timeInterval;
    if (isRunning) {
      timeInterval = setInterval(() => {
        setElapsedTime(elapsedTime + 10); // Update every 10 milliseconds
      }, 10);
      setIntervalId(timeInterval);
    } else if (intervalId) {
      clearInterval(intervalId);
    }
    return () => clearInterval(timeInterval); // Cleanup
  }, [isRunning]);

  const handleStartStopwatch = () => {
    setIsRunning(!isRunning);
  };

  const handleStopStopwatch = () => {
    setIsRunning(false);
    if (isRunning) {
      setLapTimes([...lapTimes, elapsedTime]); // Add lap time if running
    }
  };

  const handleResetStopwatch = () => {
    setElapsedTime(0);
    setIsRunning(false);
    setLapTimes([]);
  };

  const formatTime = (time) => {
    const seconds = Math.floor(time / 1000);
    const milliseconds = Math.floor(time % 1000);
    return `${seconds}:${milliseconds.toString().padStart(3, '0')}`;
  };

  // Render stopwatch display, buttons, and lap times
  return (
    <div className="stopwatch">
      <span className="display">{formatTime(elapsedTime)}</span>
      <div className="buttons">
        <button onClick={handleStartStopwatch}>{isRunning ? 'Stop' : 'Start'}</button>
        <button onClick={handleStopStopwatch}>{isRunning ? 'Lap' : 'Stop'}</button>
        <button onClick={handleResetStopwatch}>Reset</button>
      </div>
      {lapTimes.length > 0 && (
        <ul className="lap-times">
          {lapTimes.map((lapTime, index) => (
            <li key={index}>Lap {index + 1}: {formatTime(lapTime)}</li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default Stopwatch;

Explanation

  • State Management: useState variables track running state, elapsed time, interval timer reference, and lap times.

  • Time Tracking: useEffect hook manages the interval timer and updates the elapsed time every 10 milliseconds when running.

  • Start/Stop/Reset Buttons: Functions update isRunning state and optionally record lap times.

  • Formatting: formatTime function converts milliseconds to a readable format.

  • Rendering: Displays the stopwatch display, buttons, and lap times dynamically based on state.

Additional Notes

  • This is a basic example and can be further customized with styling, animations, and sound effects.

  • Consider additional features like pause functionality, target time countdown, and data persistence beyond page refreshes.

  • Integrate the stopwatch into your website or application with appropriate UI elements and interactions.

Last updated