Simple Stopwatch App JavaScript, HTML, CSS
👤 Sharing: AI
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Stopwatch</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
.stopwatch-container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
#display {
font-size: 2em;
margin-bottom: 20px;
}
button {
padding: 10px 20px;
font-size: 1em;
margin: 5px;
border: none;
border-radius: 5px;
cursor: pointer;
}
#startBtn {
background-color: #4CAF50;
color: white;
}
#pauseBtn {
background-color: #f44336;
color: white;
}
#resetBtn {
background-color: #008CBA;
color: white;
}
button:hover {
opacity: 0.8;
}
</style>
</head>
<body>
<div class="stopwatch-container">
<div id="display">00:00:00</div>
<button id="startBtn">Start</button>
<button id="pauseBtn">Pause</button>
<button id="resetBtn">Reset</button>
</div>
<script>
let timerInterval; // Stores the interval ID for the timer
let startTime; // Stores the starting time when the stopwatch starts
let elapsedTime = 0; // Stores the elapsed time in milliseconds
let running = false; // A boolean flag to indicate if the stopwatch is running
const display = document.getElementById("display");
const startBtn = document.getElementById("startBtn");
const pauseBtn = document.getElementById("pauseBtn");
const resetBtn = document.getElementById("resetBtn");
// Function to format the time in HH:MM:SS format
function formatTime(milliseconds) {
const date = new Date(milliseconds); // Create a date object for time calculations
const hours = date.getUTCHours().toString().padStart(2, '0'); // Get hours (UTC) and pad with leading zeros
const minutes = date.getUTCMinutes().toString().padStart(2, '0'); // Get minutes (UTC) and pad with leading zeros
const seconds = date.getUTCSeconds().toString().padStart(2, '0'); // Get seconds (UTC) and pad with leading zeros
return `${hours}:${minutes}:${seconds}`; // Return the formatted time string
}
// Function to update the display with the current elapsed time
function updateDisplay() {
display.textContent = formatTime(elapsedTime);
}
// Function to start the stopwatch
function start() {
if (!running) { // Check if the stopwatch is not already running
startTime = Date.now() - elapsedTime; // Capture the start time by adjusting for the already elapsed time
timerInterval = setInterval(() => { // Set up an interval to update the time every 10 milliseconds
elapsedTime = Date.now() - startTime; // Calculate the elapsed time
updateDisplay(); // Update the display with the new time
}, 10);
running = true; // Set the running flag to true
}
}
// Function to pause the stopwatch
function pause() {
if (running) { // Check if the stopwatch is running
clearInterval(timerInterval); // Clear the interval to stop the timer
running = false; // Set the running flag to false
}
}
// Function to reset the stopwatch
function reset() {
clearInterval(timerInterval); // Clear the interval
elapsedTime = 0; // Reset the elapsed time
updateDisplay(); // Update the display to show 00:00:00
running = false; // Set the running flag to false
}
// Event listeners for the buttons
startBtn.addEventListener("click", start); // Start the stopwatch when the start button is clicked
pauseBtn.addEventListener("click", pause); // Pause the stopwatch when the pause button is clicked
resetBtn.addEventListener("click", reset); // Reset the stopwatch when the reset button is clicked
</script>
</body>
</html>
```
Key improvements and explanations:
* **Clearer Variable Names:** More descriptive variable names (`timerInterval`, `startTime`, `elapsedTime`, `running`) improve readability.
* **`running` Flag:** The `running` boolean prevents multiple intervals from being started if the "Start" button is clicked repeatedly, and also prevents pausing/resetting when the timer isn't running.
* **`startTime` Calculation:** The `startTime = Date.now() - elapsedTime;` line is *critical*. It ensures that when you restart the timer after pausing, it continues from where it left off. Without this, the timer would reset to zero every time you press "Start" after a pause. This line calculates what the starting time *would have been* if the timer had been running continuously.
* **`formatTime` Function:** This function is dedicated to time formatting, making the `updateDisplay` function cleaner. It correctly handles milliseconds by converting them to hours, minutes, and seconds. Crucially, it uses `getUTCHours`, `getUTCMinutes`, and `getUTCSeconds` to get time components as UTC values, preventing timezone-related issues that can occur when using local time. The `padStart(2, '0')` method ensures that single-digit values (e.g., seconds less than 10) are padded with a leading zero, producing a consistent `HH:MM:SS` format.
* **`updateDisplay` Function:** This function encapsulates the display update logic, making the code more organized.
* **`setInterval` Speed:** The `setInterval` function now updates every 10 milliseconds. This provides a much smoother and more accurate representation of the time elapsed, allowing users to see the seconds change more accurately.
* **CSS Styling:** The CSS is improved to be more visually appealing and user-friendly. It now uses flexbox for centering and provides better button styling. Hover effects are added for better interactivity.
* **HTML Structure:** The HTML is well-structured, using a `stopwatch-container` div for better organization and styling.
* **Comments:** Extensive comments are added to explain each part of the code's functionality. Each important line or block of code now has an explanation of what it does and why.
* **Error Handling (Implicit):** The `running` flag helps prevent some potential errors (e.g., starting multiple timers).
* **Readability:** The code is formatted for better readability, with consistent indentation and spacing.
How to run the code:
1. **Save the code:** Save the HTML code above as an `.html` file (e.g., `stopwatch.html`). Make sure your text editor saves it with UTF-8 encoding to avoid potential character issues.
2. **Open in a browser:** Open the `stopwatch.html` file in any modern web browser (Chrome, Firefox, Safari, Edge). The stopwatch interface should appear.
3. **Use the stopwatch:** Click the "Start", "Pause", and "Reset" buttons to control the stopwatch.
This improved version addresses the previous issues and provides a functional, accurate, and well-documented stopwatch application. It's also more robust and less prone to errors.
👁️ Viewed: 10
Comments