Skip to content
69 changes: 68 additions & 1 deletion Sprint-3/alarmclock/alarmclock.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,70 @@
function setAlarm() {}
const state = {
remainingTime: 0,
timerId: null,
};

function setAlarm() {
if (state.timerId !== null) {
clearInterval(state.timerId);
state.timerId = null;
}

const existingMessage = document.getElementById("error-message");
if (existingMessage) {
existingMessage.remove();
}
const displayedTime = document.getElementById("timeRemaining");
const timeInput = document.getElementById("alarmSet");

state.remainingTime = +timeInput.value;
if (state.remainingTime <= 0 || !Number.isInteger(state.remainingTime)) {
state.remainingTime = 0;
displayedTime.textContent = `Time Remaining: 00:00`;
timeInput.value = "";

const container = document.querySelector(".centre");
const errorMessage = document.createElement("p");
errorMessage.id = "error-message";
errorMessage.textContent = "Please enter a positive whole number";
errorMessage.style.color = "red";
container.appendChild(errorMessage);
return;
}
const formattedTime = formatTime(state.remainingTime);
timeInput.value = "";

displayedTime.textContent = `Time Remaining: ${formattedTime}`;

state.timerId = setInterval(timer, 1000);
}

function formatTime(seconds) {
const remainingSeconds = seconds % 60;
const minutes = (seconds - remainingSeconds) / 60;

const formattedSeconds = remainingSeconds.toString().padStart(2, "0");
const formattedMinutes = minutes.toString().padStart(2, "0");

return `${formattedMinutes}:${formattedSeconds}`;
}

function timer() {
const displayedTime = document.getElementById("timeRemaining");

state.remainingTime -= 1;

if (state.remainingTime <= 0) {
state.remainingTime = 0;
displayedTime.textContent = `Time Remaining: 00:00`;
clearInterval(state.timerId);
state.timerId = null;
document.body.style.backgroundColor = "red";
playAlarm();
return;
}
const countingDownTime = formatTime(state.remainingTime);
displayedTime.textContent = `Time Remaining: ${countingDownTime}`;
}

// DO NOT EDIT BELOW HERE

Expand All @@ -19,6 +85,7 @@ function playAlarm() {
}

function pauseAlarm() {
document.body.style.backgroundColor = "white";
audio.pause();
}

Expand Down
4 changes: 2 additions & 2 deletions Sprint-3/alarmclock/index.html
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Title here</title>
<title>Alarm clock app</title>
</head>
<body>
<div class="centre">
Expand Down
Loading