To implement a timer in JavaScript that allows you to specify the duration in hours, minutes, and seconds, you can use the following code:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Timer</title>
</head>
<body>
<h1>Custom Timer</h1>
<div id="timer"></div>
<script>
// Function to start the timer
function startTimer(hours, minutes, seconds) {
// Calculate the total duration in seconds
let totalSeconds = hours * 3600 + minutes * 60 + seconds;
// Update the timer display every second
let timerInterval = setInterval(function() {
// Calculate hours, minutes, and seconds remaining
let hoursRemaining = Math.floor(totalSeconds / 3600);
let minutesRemaining = Math.floor((totalSeconds % 3600) / 60);
let secondsRemaining = totalSeconds % 60;
// Display the timer
document.getElementById('timer').innerText = `${hoursRemaining.toString().padStart(2, '0')}:${minutesRemaining.toString().padStart(2, '0')}:${secondsRemaining.toString().padStart(2, '0')}`;
// Decrement totalSeconds
totalSeconds--;
// Check if the timer has reached 0
if (totalSeconds < 0) {
clearInterval(timerInterval);
document.getElementById('timer').innerText = "Timer Expired!";
}
}, 1000); // Update every second
}
// Start the timer with the specified duration (e.g., 1 hour, 30 minutes, 45 seconds)
startTimer(1, 30, 45);
</script>
</body>
</html>
```
In this code:
- The `startTimer` function takes three parameters: `hours`, `minutes`, and `seconds`.
- It calculates the total duration in seconds based on the input parameters.
- It then starts an interval that updates the timer display every second.
- Inside the interval, it calculates the remaining hours, minutes, and seconds and updates the timer display accordingly.
- When the timer reaches 0, it stops the interval and displays "Timer Expired!".
You can adjust the `startTimer` function call at the bottom to set the desired duration in hours, minutes, and seconds.