-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathCountdown Timer with Start
100 lines (100 loc) · 2.82 KB
/
Countdown Timer with Start
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Countdown Timer</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="timer-container">
<h1>Countdown Timer</h1>
<form id="timerForm">
<input type="number" id="secondsInput" placeholder="Enter seconds" required>
<button type="submit">Start Timer</button>
</form>
<p id="timerDisplay">0:00</p>
<button id="stopButton" disabled>Stop</button>
<button id="resetButton" disabled>Reset</button>
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.timer-container {
text-align: center;
background-color: #f0f0f0;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
form {
display: flex;
flex-direction: column;
gap: 10px;
margin-bottom: 20px;
}
input, button {
padding: 10px;
font-size: 16px;
}
p {
font-size: 36px;
margin-top: 20px;
}
JavaScript:
let timer;
let timeLeft;
let isRunning = false;
document.getElementById('timerForm').addEventListener('submit', function(event) {
event.preventDefault();
clearInterval(timer);
timeLeft = parseInt(document.getElementById('secondsInput').value);
updateDisplay();
startTimer();
document.getElementById('stopButton').disabled = false;
document.getElementById('resetButton').disabled = false;
});
document.getElementById('stopButton').addEventListener('click', function() {
clearInterval(timer);
isRunning = false;
document.getElementById('stopButton').disabled = true;
});
document.getElementById('resetButton').addEventListener('click', function() {
clearInterval(timer);
timeLeft = 0;
updateDisplay();
document.getElementById('stopButton').disabled = true;
document.getElementById('resetButton').disabled = true;
});
function startTimer() {
if (!isRunning) {
timer = setInterval(function() {
if (timeLeft > 0) {
timeLeft--;
updateDisplay();
} else {
clearInterval(timer);
alert('Time is up!');
document.getElementById('stopButton').disabled = true;
document.getElementById('resetButton').disabled = true;
}
}, 1000);
isRunning = true;
}
}
function updateDisplay() {
const minutes = Math.floor(timeLeft / 60).toString().padStart(1, '0');
const seconds = (timeLeft % 60).toString().padStart(2, '0');
document.getElementById('timerDisplay').textContent = `${minutes}:${seconds}`;
}
updateDisplay();