-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathalarm.js
More file actions
91 lines (76 loc) · 2.25 KB
/
alarm.js
File metadata and controls
91 lines (76 loc) · 2.25 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
const ampm = document.getElementById("ampm");
const hour = document.getElementById("hr");
const mins = document.getElementById("min");
const check = document.getElementById("check");
const timerButton = document.getElementById("timerbtn");
const snoozeBtn = document.getElementById("snooze");
const timerSecs = document.getElementById("timer-secs");
const timerMins = document.getElementById("timer-mins");
const currentCount = parseInt(timerMins.textContent);
const sound = new Audio("alarm.mp3");
sound.loop = true;
let num = currentCount * 60;
let alarm;
let timer;
let alarmElement;
let status = true;
check.addEventListener("click", (e) => {
if (e.target.checked) {
playAlarm();
}
})
snoozeBtn.addEventListener("click", () => {
sound.pause();
sound.currentTime = 0;
clearTimeout(alarm);
setTimeout(playAlarm, 5000);
});
timerButton.addEventListener("click", () => {
if (status) {
Timer();
timerButton.textContent = "Stop Timer";
status = false;
} else {
clearTimeout(timer);
timerButton.textContent = "Start Timer";
status = true;
}
});
function addZero(num) {
return num < 10 ? "0" + num : num;
}
function playAlarm() {
const now = new Date();
const hours = now.getHours() < 12 ? "AM" : "PM";
const currentTime = addZero(now.getHours()) + ":" + addZero(now.getMinutes()) + " " + hours;
alarmElement = hour.textContent + ":" + mins.textContent + " " + ampm.textContent;
if (currentTime === alarmElement) {
sound.play();
if (check.checked === false) {
sound.pause();
sound.currentTime = 0;
}
}
alarm = setTimeout(playAlarm, 1000);
}
function snoozeAlarm() {
const now = new Date();
const hours = now.getHours() < 12 ? "AM" : "PM";
const currentTime = addZero(now.getHours()) + ":" + addZero(now.getMinutes()) + " " + hours;
alarmElement = hour.textContent + ":" + mins.textContent + " " + ampm.textContent;
if (currentTime === alarmElement && check.checked) {
snoozeBtn.style.visibility = "visible";
}
if (check.checked === false) {
snoozeBtn.style.visibility = "hidden";
}
}
setInterval(snoozeAlarm, 1000);
function Timer() {
let minutes = Math.floor(num / 60);
let seconds = num % 60;
timerMins.textContent = addZero(minutes);
timerSecs.textContent = addZero(seconds);
num++;
timer = setTimeout(Timer, 1000);
}