1+ let countdown = null ;
2+
13function setAlarm ( ) {
2- let timeRemaining = document . getElementById ( "alarmSet" ) . value ;
3- const timeDisplay = document . getElementById ( "timeRemaining" ) ;
4-
5- // Create a reusable function to update the text on the screen
6- const updateDisplay = ( time ) => {
7- let minutes = Math . floor ( time / 60 )
8- . toString ( )
9- . padStart ( 2 , "0" ) ;
10- let seconds = ( time % 60 ) . toString ( ) . padStart ( 2 , "0" ) ;
11- timeDisplay . innerText = "Time Remaining: " + minutes + ":" + seconds ;
4+ let secondsLeft = parseInt ( document . getElementById ( "alarmSet" ) . value , 10 ) ;
5+ const timeDisplay = document . getElementById ( "timeRemaining" ) ;
6+
7+ if ( isNaN ( secondsLeft ) || secondsLeft <= 0 ) {
8+ timeDisplay . innerText = "Time Remaining: 00:00" ;
9+ return ;
10+ }
11+
12+ if ( countdown !== null ) {
13+ clearInterval ( countdown ) ;
14+ }
15+
16+ const updateDisplay = ( time ) => {
17+ let minutes = Math . floor ( time / 60 ) . toString ( ) . padStart ( 2 , "0" ) ;
18+ let seconds = ( time % 60 ) . toString ( ) . padStart ( 2 , "0" ) ;
19+ timeDisplay . innerText = "Time Remaining: " + minutes + ":" + seconds ;
1220 } ;
1321
14- // STEP 1: Display the starting time IMMEDIATELY
15- updateDisplay ( timeRemaining ) ;
22+ updateDisplay ( secondsLeft ) ;
1623
17- // STEP 2: Start the interval
18- const countdown = setInterval ( ( ) => {
19- timeRemaining -- ;
20- updateDisplay ( timeRemaining ) ;
24+ countdown = setInterval ( ( ) => {
25+ secondsLeft = secondsLeft - 1 ;
26+ updateDisplay ( secondsLeft ) ;
2127
22- if ( timeRemaining <= 0 ) {
23- clearInterval ( countdown ) ;
24- playAlarm ( ) ;
28+ if ( secondsLeft <= 0 ) {
29+ clearInterval ( countdown ) ;
30+ countdown = null ;
31+ playAlarm ( ) ;
2532 }
26- } , 1000 ) ;
33+ } , 1000 ) ;
2734}
2835
2936// DO NOT EDIT BELOW HERE
@@ -48,4 +55,4 @@ function pauseAlarm() {
4855 audio . pause ( ) ;
4956}
5057
51- window . onload = setup ;
58+ window . onload = setup ;
0 commit comments