Stopwatch Script
Track elapsed time. This script provides the core logic for a stopwatch, handling the state management between running, paused, and reset modes.
00:00:00
Copy the Script
<div id="stopwatch">00:00:00</div>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
<button onclick="reset()">Reset</button>
<script>
var timer;
var ele = document.getElementById('stopwatch');
var seconds = 0;
var minutes = 0;
var hours = 0;
function update() {
seconds++;
if (seconds >= 60) { seconds = 0; minutes++; }
if (minutes >= 60) { minutes = 0; hours++; }
var h = hours ? (hours > 9 ? hours : "0" + hours) : "00";
var m = minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00";
var s = seconds > 9 ? seconds : "0" + seconds;
ele.innerHTML = h + ":" + m + ":" + s;
}
function start() {
if(!timer) timer = setInterval(update, 1000);
}
function stop() {
clearInterval(timer);
timer = null;
}
function reset() {
stop();
seconds = 0; minutes = 0; hours = 0;
ele.innerHTML = "00:00:00";
}
</script>
Frequently Asked Questions
JavaScript timers can drift slightly over long periods (hours) due to browser throttling. For casual use (minutes), it is perfectly accurate.
Yes, but modern browsers might slow down the update rate (frame rate) of background tabs to save battery. The actual time calculation will correct itself when you return.
Yes. You can add a button that pushes the current `innerHTML` of the timer to a list (`
- `) without stopping the interval.