Digital Clock and Stopwatch in JavaScript


Features:

  • Real-time Digital Clock
  • Functional Stopwatch with Start, Stop, Reset
  • Simple and responsive UI


Folder Structure

clock-stopwatch/
├── index.html
├── style.css
└── script.js


HTML: index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Digital Clock & Stopwatch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Digital Clock</h1>
<div id="clock" class="display">00:00:00</div>

<h1>Stopwatch</h1>
<div id="stopwatch" class="display">00:00:00</div>
<div class="buttons">
<button onclick="startStopwatch()">Start</button>
<button onclick="stopStopwatch()">Stop</button>
<button onclick="resetStopwatch()">Reset</button>
</div>
</div>

<script src="script.js"></script>
</body>
</html>


CSS: style.css

body {
  margin: 0;
  font-family: 'Segoe UI', sans-serif;
  background: #f0f4f7;
  display: flex;
  justify-content: center;
  padding: 40px;
}

.container {
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  text-align: center;
}

h1 {
  margin-bottom: 10px;
}

.display {
  font-size: 2.5rem;
  background: #222;
  color: #0f0;
  padding: 10px 30px;
  border-radius: 10px;
  margin: 15px auto;
  display: inline-block;
  font-family: 'Courier New', monospace;
}

.buttons button {
  margin: 10px;
  padding: 10px 20px;
  font-size: 1rem;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.buttons button:hover {
  background-color: #0056b3;
}


JavaScript: script.js

// DIGITAL CLOCK
function updateClock() {
  const now = new Date();
  const time = now.toLocaleTimeString('en-US', { hour12: false });
  document.getElementById('clock').textContent = time;
}

setInterval(updateClock, 1000);
updateClock(); // initialize

// STOPWATCH
let stopwatchInterval;
let elapsedSeconds = 0;
let running = false;

function formatTime(seconds) {
  const hrs = String(Math.floor(seconds / 3600)).padStart(2, '0');
  const mins = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
  const secs = String(seconds % 60).padStart(2, '0');
  return `${hrs}:${mins}:${secs}`;
}

function updateStopwatch() {
  document.getElementById('stopwatch').textContent = formatTime(elapsedSeconds);
}

function startStopwatch() {
  if (!running) {
    running = true;
    stopwatchInterval = setInterval(() => {
      elapsedSeconds++;
      updateStopwatch();
    }, 1000);
  }
}

function stopStopwatch() {
  running = false;
  clearInterval(stopwatchInterval);
}

function resetStopwatch() {
  stopStopwatch();
  elapsedSeconds = 0;
  updateStopwatch();
}

// Initialize display
updateStopwatch();