|
1 | | -let countdown; |
| 1 | +let countdownId; |
| 2 | + |
| 3 | + // moved to outer scope, takes seconds as a parameter |
| 4 | + function updateDisplay(seconds) { |
| 5 | + const minutes = Math.floor(seconds / 60); |
| 6 | + const remainingSeconds = seconds % 60; |
| 7 | + document.getElementById("timeRemaining").textContent = |
| 8 | + `Time Remaining: ${String(minutes).padStart(2, "0")}:${String(remainingSeconds).padStart(2, "0")}`; |
| 9 | + } |
2 | 10 |
|
3 | 11 | // reset before starting new countdown |
4 | 12 | function resetAlarm() { |
5 | | - clearInterval(countdown); |
6 | | - audio.pause(); |
7 | | - document.getElementById("timeRemaining").textContent = "Time Remaining: 00:00"; |
| 13 | + clearInterval(countdownId); |
| 14 | + updateDisplay(0); // replaces the manual textContent line |
8 | 15 | document.body.classList.toggle("alarm-activated", false); |
9 | 16 | } |
10 | 17 |
|
11 | 18 | function setAlarm() { |
12 | 19 | let seconds = parseInt(document.getElementById("alarmSet").value); |
13 | 20 |
|
14 | 21 | if (!seconds || seconds < 1) { |
15 | | - alert("The number of seconds must be more than 0 please"); |
| 22 | + alert("The number of seconds must be higher than 0 please"); |
16 | 23 | return; |
17 | 24 | } |
18 | | - function updateDisplay() { |
19 | | - const minutes = Math.floor(seconds / 60); |
20 | | - const remainingSeconds = seconds % 60; |
21 | | - document.getElementById("timeRemaining").textContent = |
22 | | - `Time Remaining: ${String(minutes).padStart(2, "0")}:${String(remainingSeconds).padStart(2, "0")}`; |
23 | | - } |
24 | | - |
25 | | - updateDisplay(); // update immediately on click |
26 | 25 |
|
27 | | - // code to reset background |
28 | | - function pauseAlarm() { |
29 | | - audio.pause(); |
30 | | - document.body.classList.toggle("alarm-activated", false); |
31 | | - } |
| 26 | + updateDisplay(seconds); |
| 27 | + // pass seconds as argument and update immediately on click |
32 | 28 |
|
33 | | - countdown = setInterval(() => { |
| 29 | + countdownId = setInterval(() => { |
34 | 30 | seconds--; |
35 | | - updateDisplay(); |
| 31 | + updateDisplay(seconds); |
| 32 | + // pass seconds as argument |
36 | 33 |
|
37 | 34 | if (seconds <= 0) { |
38 | | - clearInterval(countdown); |
| 35 | + clearInterval(countdownId); |
39 | 36 | playAlarm(); |
40 | 37 | document.body.classList.toggle("alarm-activated", true); |
41 | 38 | } |
|
0 commit comments