forked from CodeYourFuture/Module-Data-Groups
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalarmclock.js
More file actions
93 lines (74 loc) · 2.04 KB
/
Copy pathalarmclock.js
File metadata and controls
93 lines (74 loc) · 2.04 KB
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
let timer = null;
let totalSeconds = 0;
function formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
}
function parseInputTime(value) {
if (!/^\d{2}:\d{2}$/.test(value)) return null;
const [m, s] = value.split(":").map(Number);
if (s > 59) return null;
return m * 60 + s;
}
function updateDisplay() {
const heading = document.getElementById("timeRemaining");
const input = document.getElementById("alarmSet");
totalSeconds = Math.max(0, totalSeconds);
const formatted = formatTime(totalSeconds);
input.value = formatted;
heading.innerHTML = `Time Remaining:<br><br>${formatted}`;
}
function incrementTime(amount) {
totalSeconds = Math.max(0, totalSeconds + amount);
updateDisplay();
}
function resetAlarmState() {
if (timer) clearInterval(timer);
timer = null;
audio.pause();
audio.currentTime = 0;
}
function setAlarm() {
resetAlarmState();
const input = document.getElementById("alarmSet");
const parsed = parseInputTime(input.value);
if (parsed === null) {
alert("Use MM:SS format");
return;
}
totalSeconds = parsed;
updateDisplay();
if (timer) clearInterval(timer);
timer = setInterval(() => {
totalSeconds--;
totalSeconds = Math.max(0, totalSeconds);
updateDisplay();
if (totalSeconds === 0) {
clearInterval(timer);
timer = null;
playAlarm();
}
}, 1000);
}
function stopTimer() {
if (timer) clearInterval(timer);
timer = null;
totalSeconds = 0;
updateDisplay();
audio.pause();
}
document.getElementById("up").addEventListener("click", () => incrementTime(5));
document
.getElementById("down")
.addEventListener("click", () => incrementTime(-5));
document.getElementById("set").addEventListener("click", setAlarm);
document.getElementById("stop").addEventListener("click", stopTimer);
// DO NOT EDIT BELOW HERE
var audio = new Audio("alarmsound.mp3");
function playAlarm() {
audio.play();
}
function pauseAlarm() {
audio.pause();
}