|
1 | 1 | let intervalId = null; |
2 | 2 | let totalSeconds = 0; |
| 3 | +const input = document.getElementById("alarmSet"); |
| 4 | +const timeRemaining = document.getElementById("timeRemaining"); |
| 5 | +const message = document.getElementById("message"); |
3 | 6 |
|
4 | | -function formatTime(seconds){ |
5 | | - const minutes = Math.floor(seconds/ 60); |
| 7 | +function formatTime(seconds) { |
| 8 | + const minutes = Math.floor(seconds / 60); |
6 | 9 | const secs = seconds % 60; |
7 | | - return `${string(minutes).padStart(2,"0")}:${String(secs).padStart(2,"0")}`; |
| 10 | + return `${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`; |
| 11 | +} |
| 12 | +function updateDisplay() { |
| 13 | + timeRemaining.textContent = `Time Remaining: ${formatTime(totalSeconds)}`; |
| 14 | +} |
8 | 15 |
|
| 16 | +function resetAlarm() { |
| 17 | + clearInterval(intervalId); |
| 18 | + intervalId = null; |
| 19 | + audio.pause(); |
| 20 | + audio.currentTime = 0; |
9 | 21 | } |
| 22 | +function getTime() { |
| 23 | + const time = Number(input.value); |
| 24 | + if (!(Number.isInteger(time) && time >= 1)) { |
| 25 | + message.textContent = "Enter a valid number"; |
| 26 | + return null; |
| 27 | + } |
| 28 | + return time; |
| 29 | +} |
| 30 | + |
10 | 31 | function setAlarm() { |
11 | | - // clearing any previous countdown |
12 | | - if (intervalId !== null){ |
13 | | - clearInterval(intervalId) |
| 32 | + const time = getTime(); |
| 33 | + if (time === null) { |
| 34 | + return; |
14 | 35 | } |
15 | | - const input = document.getElementById("alarmSet"); |
16 | | - totalSeconds = Number(input.value); |
17 | 36 |
|
18 | | - document.getElementById("timeRemaining").textContent = `Time Remaining: ${formatTime(totalSeconds)}`; |
| 37 | + resetAlarm(); |
| 38 | + totalSeconds = time; |
| 39 | + updateDisplay(); |
19 | 40 |
|
20 | 41 | intervalId = setInterval(() => { |
21 | 42 | totalSeconds--; |
22 | | - document.getElementById("timeRemaining").textContent = `Time Remaining: ${formatTime(totalSeconds)}`; |
| 43 | + updateDisplay(); |
23 | 44 |
|
24 | 45 | if (totalSeconds <= 0) { |
25 | 46 | clearInterval(intervalId); |
26 | 47 | intervalId = null; |
27 | 48 | playAlarm(); |
28 | 49 | } |
29 | 50 | }, 1000); |
30 | | - |
31 | 51 | } |
32 | 52 |
|
33 | 53 | // DO NOT EDIT BELOW HERE |
|
0 commit comments