1- function setAlarm ( ) { }
1+ var audio = new Audio ( "alarmsound.mp3" ) ;
22
3- // DO NOT EDIT BELOW HERE
3+ let timeRemaining = 0 ;
4+ let countdownInterval = null ;
5+ let hasPlayed = false ;
46
5- var audio = new Audio ( "alarmsound.mp3" ) ;
7+ function setAlarm ( ) {
8+ const input = document . getElementById ( "alarmSet" ) . value ;
69
7- function setup ( ) {
8- document . getElementById ( "set" ) . addEventListener ( "click" , ( ) => {
9- setAlarm ( ) ;
10- } ) ;
10+ timeRemaining = parseInt ( input , 10 ) ;
11+
12+ if ( isNaN ( timeRemaining ) || timeRemaining <= 0 ) {
13+ alert ( "Please enter a valid number greater than 0" ) ;
14+ return ;
15+ }
16+
17+ hasPlayed = false ;
18+ updateDisplay ( ) ;
19+
20+ if ( countdownInterval ) {
21+ clearInterval ( countdownInterval ) ;
22+ }
23+
24+ countdownInterval = setInterval ( ( ) => {
25+ timeRemaining -- ;
26+
27+ // Play alarm at 10 seconds remaining (or immediately if less than 10)
28+ if ( ! hasPlayed && ( timeRemaining === 10 || timeRemaining < 10 ) ) {
29+ playAlarm ( ) ;
30+ hasPlayed = true ;
31+ }
1132
12- document . getElementById ( "stop" ) . addEventListener ( "click" , ( ) => {
13- pauseAlarm ( ) ;
14- } ) ;
33+ if ( timeRemaining <= 0 ) {
34+ timeRemaining = 0 ;
35+ updateDisplay ( ) ;
36+ clearInterval ( countdownInterval ) ;
37+ return ;
38+ }
39+
40+ updateDisplay ( ) ;
41+ } , 1000 ) ;
42+ } // ✅ properly closed function
43+
44+ function updateDisplay ( ) {
45+ const display = document . getElementById ( "timeRemaining" ) ;
46+
47+ const minutes = String ( Math . floor ( timeRemaining / 60 ) ) . padStart ( 2 , "0" ) ;
48+ const seconds = String ( timeRemaining % 60 ) . padStart ( 2 , "0" ) ;
49+
50+ display . textContent = `Time Remaining: ${ minutes } :${ seconds } ` ;
51+ }
52+
53+ function setup ( ) {
54+ document . getElementById ( "set" ) . addEventListener ( "click" , setAlarm ) ;
55+ document . getElementById ( "stop" ) . addEventListener ( "click" , pauseAlarm ) ;
1556}
1657
1758function playAlarm ( ) {
@@ -20,6 +61,11 @@ function playAlarm() {
2061
2162function pauseAlarm ( ) {
2263 audio . pause ( ) ;
64+ audio . currentTime = 0 ;
65+
66+ if ( countdownInterval ) {
67+ clearInterval ( countdownInterval ) ;
68+ }
2369}
2470
25- window . onload = setup ;
71+ window . onload = setup ;
0 commit comments