I can help you create a simple stopwatch with start, stop, and pause functions using plain JavaScript.
This simple HTML page includes a display area to show the elapsed time, and three buttons for start, pause, and stop actions.
The JavaScript code defines functions for handling these actions and updating the display accordingly. The ‘setInterval‘ function is used to update the stopwatch every second when it is running.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stopwatch</title>
<style>
body {
text-align: center;
margin: 50px;
font-family: Arial, sans-serif;
}
#display {
font-size: 2em;
margin-bottom: 20px;
}
#controls {
margin-top: 20px;
}
</style>
</head>
<body>
<div id="display">00:00:00</div>
<div id="controls">
<button onclick="startStopwatch()">Start</button>
<button onclick="pauseStopwatch()">Pause</button>
<button onclick="stopStopwatch()">Stop</button>
</div>
<script>
let timer;
let isRunning = false;
let seconds = 0;
let minutes = 0;
let hours = 0;
function startStopwatch() {
if (!isRunning) {
timer = setInterval(updateStopwatch, 1000);
isRunning = true;
}
}
function pauseStopwatch() {
if (isRunning) {
clearInterval(timer);
isRunning = false;
}
}
function stopStopwatch() {
clearInterval(timer);
isRunning = false;
seconds = 0;
minutes = 0;
hours = 0;
updateDisplay();
}
function updateStopwatch() {
seconds++;
if (seconds === 60) {
seconds = 0;
minutes++;
if (minutes === 60) {
minutes = 0;
hours++;
}
}
updateDisplay();
}
function updateDisplay() {
const formattedTime = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
document.getElementById('display').textContent = formattedTime;
}
function pad(value) {
return value < 10 ? `0${value}` : value;
}
</script>
</body>
</html>