Timer CountdownJavaScript

👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html>
<head>
<title>Countdown Timer</title>
<style>
body {
  font-family: sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f0f0;
}

.container {
  text-align: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

#timer {
  font-size: 3em;
  margin-bottom: 20px;
}

input[type="number"] {
  padding: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 80px;
}

button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #3e8e41;
}
</style>
</head>
<body>

<div class="container">
  <h1>Countdown Timer</h1>
  <div id="timer">00:00</div>

  <label for="minutes">Minutes:</label>
  <input type="number" id="minutes" min="0" value="1">

  <label for="seconds">Seconds:</label>
  <input type="number" id="seconds" min="0" max="59" value="0">

  <button onclick="startTimer()">Start Countdown</button>
</div>

<script>
let countdownInterval;
let timeLeft;

function startTimer() {
  const minutes = parseInt(document.getElementById("minutes").value, 10) || 0;
  const seconds = parseInt(document.getElementById("seconds").value, 10) || 0;

  if (isNaN(minutes) || isNaN(seconds) || (minutes === 0 && seconds === 0)) {
    alert("Please enter a valid time.");
    return;
  }

  timeLeft = minutes * 60 + seconds;

  clearInterval(countdownInterval); // Clear any existing timer
  countdownInterval = setInterval(updateTimer, 1000);

  updateTimer(); // Update immediately on start
}

function updateTimer() {
  let minutes = Math.floor(timeLeft / 60);
  let seconds = timeLeft % 60;

  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

  document.getElementById("timer").innerText = minutes + ":" + seconds;

  timeLeft--;

  if (timeLeft < 0) {
    clearInterval(countdownInterval);
    document.getElementById("timer").innerText = "Time's up!";
  }
}
</script>

</body>
</html>
```
👁️ Viewed: 152

Comments