About this snippet

Track time precisely with this stopwatch widget. It features start, stop, and reset functionality using vanilla JavaScript, and the display is formatted to show double digits for a professional look.

Size
2.2 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
290

Collections

<div class="stopwatch">
  <div class="time-display" id="display">00:00:00</div>
  <div class="controls">
    <button id="startBtn" class="btn start">Start</button>
    <button id="stopBtn" class="btn stop">Stop</button>
    <button id="resetBtn" class="btn reset">Reset</button>
  </div>
</div>
.stopwatch {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  background: #1f2937;
  padding: 30px;
  border-radius: 20px;
  text-align: center;
  width: 300px;
  margin: 0 auto;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
.time-display {
  font-size: 3.5rem;
  font-weight: 700;
  color: #fff;
  font-variant-numeric: tabular-nums;
  margin-bottom: 20px;
  text-shadow: 0 0 10px rgba(255,255,255,0.1);
}
.controls {
  display: flex;
  gap: 10px;
  justify-content: center;
}
.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.1s, opacity 0.2s;
  font-size: 1rem;
}
.btn:active {
  transform: scale(0.95);
}
.start {
  background: #10b981;
  color: white;
}
.stop {
  background: #ef4444;
  color: white;
}
.reset {
  background: #4b5563;
  color: white;
}
let [seconds, minutes, hours] = [0, 0, 0];
let display = document.getElementById("display");
let timer = null;

function stopwatch() {
  seconds++;
  if (seconds == 60) {
    seconds = 0;
    minutes++;
    if (minutes == 60) {
      minutes = 0;
      hours++;
    }
  }

  let h = hours < 10 ? "0" + hours : hours;
  let m = minutes < 10 ? "0" + minutes : minutes;
  let s = seconds < 10 ? "0" + seconds : seconds;

  display.innerHTML = h + ":" + m + ":" + s;
}

function startTimer() {
  if (timer !== null) {
    clearInterval(timer);
  }
  timer = setInterval(stopwatch, 1000);
}

function stopTimer() {
  clearInterval(timer);
}

function resetTimer() {
  clearInterval(timer);
  [seconds, minutes, hours] = [0, 0, 0];
  display.innerHTML = "00:00:00";
}

document.getElementById("startBtn").addEventListener("click", startTimer);
document.getElementById("stopBtn").addEventListener("click", stopTimer);
document.getElementById("resetBtn").addEventListener("click", resetTimer);
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save