Skip to content

Commit 2ae42af

Browse files
committed
alarm clock function
1 parent 264f3e1 commit 2ae42af

File tree

1 file changed

+66
-11
lines changed

1 file changed

+66
-11
lines changed

Sprint-3/alarmclock/alarmclock.js

Lines changed: 66 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,72 @@
1-
function setAlarm() {}
1+
let timer = null;
2+
let totalSeconds = 0;
23

3-
// DO NOT EDIT BELOW HERE
4+
function formatTime(seconds) {
5+
const mins = Math.floor(seconds / 60);
6+
const secs = seconds % 60;
7+
return `${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
8+
}
49

5-
var audio = new Audio("alarmsound.mp3");
10+
function parseInputTime(value) {
11+
if (!/^\d{2}:\d{2}$/.test(value)) return null;
12+
const [m, s] = value.split(":").map(Number);
13+
if (s > 59) return null;
14+
return m * 60 + s;
15+
}
616

7-
function setup() {
8-
document.getElementById("set").addEventListener("click", () => {
9-
setAlarm();
10-
});
17+
function updateDisplay() {
18+
document.getElementById("alarmSet").value = formatTime(totalSeconds);
19+
document.getElementById("timeRemaining").textContent = `Time Remaining: ${formatTime(totalSeconds)}`;
20+
}
1121

12-
document.getElementById("stop").addEventListener("click", () => {
13-
pauseAlarm();
14-
});
22+
function incrementTime(amount) {
23+
totalSeconds += amount;
24+
if (totalSeconds < 0) totalSeconds = 0;
25+
updateDisplay();
1526
}
1627

28+
function setAlarm() {
29+
const input = document.getElementById("alarmSet");
30+
const parsed = parseInputTime(input.value);
31+
if (parsed === null) {
32+
alert("Use MM:SS format");
33+
return;
34+
}
35+
36+
totalSeconds = parsed;
37+
updateDisplay();
38+
39+
if (timer) clearInterval(timer);
40+
41+
timer = setInterval(() => {
42+
totalSeconds--;
43+
updateDisplay();
44+
if (totalSeconds <= 0) {
45+
clearInterval(timer);
46+
timer = null;
47+
playAlarm();
48+
}
49+
}, 1000);
50+
}
51+
52+
function stopTimer() {
53+
if (timer) {
54+
clearInterval(timer);
55+
timer = null;
56+
}
57+
totalSeconds = 0;
58+
updateDisplay();
59+
pauseAlarm();
60+
}
61+
62+
// attach to window so HTML buttons can call them
63+
window.incrementTime = incrementTime;
64+
window.setAlarm = setAlarm;
65+
window.stopTimer = stopTimer;
66+
67+
// DO NOT EDIT BELOW HERE
68+
var audio = new Audio("alarmsound.mp3");
69+
1770
function playAlarm() {
1871
audio.play();
1972
}
@@ -22,4 +75,6 @@ function pauseAlarm() {
2275
audio.pause();
2376
}
2477

25-
window.onload = setup;
78+
window.playAlarm = playAlarm;
79+
window.pauseAlarm = pauseAlarm;
80+

0 commit comments

Comments
 (0)