Dev Helpers
← Back

Start stop stopwatch

Import and render <StartStopStopwatch /> in a React project.

Open this example in the interactive library

Live preview

Source code

// components/StartStopStopwatch.tsx

import { useState, useEffect } from "react";

export default function StartStopStopwatch() {
  const [running, run] = useState(false);
  const [ticks, set] = useState(0);
  useEffect(() => {
    if (!running) return;
    const start = Date.now() - ticks * 1000;
    const timer = setInterval(() => set(Math.floor((Date.now() - start) / 1000)), 200);
    return () => clearInterval(timer);
  }, [running]);
  return (
    <div>
      <output>{ticks}s</output>
      <button onClick={() => run(!running)}>{running ? "Stop" : "Start"}</button>
    </div>
  );
}