Recently, I've been dabbling in creating a basic stopwatch script using JavaScript to showcase the elapsed seconds, minutes, and hours.
The desired time format is:
hh:mm:ss
In my quest to achieve this with JavaScript, I encountered a roadblock. The challenge I faced was formatting numbers to include a leading zero for single-digit values. While I managed to add a leading "0" for the seconds
, I struggled to do the same for minutes
and hours
.
The issue stemmed from inadvertently adding multiple "0"s within each iteration of the setInterval()
function, resulting in extended strings of "0"s before the actual minutes
or hours
values.
I'm puzzled as to why this occurred selectively for the minutes
and hours
sections while it didn't affect the seconds
. Despite utilizing the same logic across all three sections, the discrepancy remains elusive.
The anomaly gets more intriguing as the surplus "0"s only start appearing after two seconds into the timer. Here's the snippet of code I drafted for the stopwatch script. Any insights on rectifying this deviation would be greatly appreciated.
let seconds = 0;
let minutes = 0;
let hours = 0;
function stopWatch(){
//Increment seconds per tick of the stopwatch
seconds++;
//Check for necessary increment in minutes or hours (every 60 seconds or 60 minutes)
if(seconds % 60 == 0){
seconds = 0;
minutes++;
if(minutes % 60 == 0){
minutes = 0;
hours++;
}
}
//Add a leading 0 if seconds, minutes, or hours are less than 10
if(seconds < 10){
seconds = "0" + seconds;
}
if(minutes < 10){
minutes = "0" + minutes;
}
if(hours < 10){
hours = "0" + hours;
}
//Display the results in the HTML "display" div
document.getElementById("display").innerHTML = hours + ":" + minutes + ":" + seconds;
}
//Run the stopWatch() function every second (1000ms)
window.setInterval(stopWatch, 1000);
<div id="display">00:00:00</div>
For simplicity, I retained the <script></script>
tags within the HTML document. Once I streamline the functionality, I intend to transfer the script to a separate script.js
file and perhaps introduce buttons for starting, stopping, and resetting the stopwatch.