File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const timeRemaining = document . getElementById ( "timeRemaining" ) ;
2+ let timer ;
3+
14function setAlarm ( ) {
2- // Get the input element
3- const alarmSetInput = document . getElementById ( "alarmSet" ) ;
4-
5- // Get the number of seconds
6- const seconds = Number ( alarmSetInput . value ) ;
7-
8- // Validate input
9- if ( seconds <= 0 || isNaN ( seconds ) ) {
10- alert ( "Please enter a valid number." ) ;
11- return ;
12- }
13-
14- // Wait the specified number of seconds
15- setTimeout ( ( ) => {
16- playAlarm ( )
17- } , seconds * 1000 ) ;
5+ const alarmSetInput = document . getElementById ( "alarmSet" ) ;
6+ let seconds = Number ( alarmSetInput . value ) ;
7+
8+ if ( seconds <= 0 || isNaN ( seconds ) ) {
9+ alert ( "Please enter a valid number." ) ;
10+ return ;
11+ }
12+
13+ // Stop a previous countdown if there is one
14+ clearInterval ( timer ) ;
15+
16+ timer = setInterval ( ( ) => {
17+
18+ const minutes = Math . floor ( seconds / 60 ) ;
19+ const secs = seconds % 60 ;
20+
21+ timeRemaining . textContent =
22+ `Time Remaining: ${ String ( minutes ) . padStart ( 2 , "0" ) } :${ String ( secs ) . padStart ( 2 , "0" ) } ` ;
23+
24+ if ( seconds <= 0 ) {
25+ clearInterval ( timer ) ;
26+ playAlarm ( ) ;
27+ return ;
28+ }
29+
30+ seconds -- ;
31+
32+ } , 1000 ) ;
1833}
1934
2035document . getElementById ( "set" ) . addEventListener ( "click" , setAlarm ) ;
@@ -42,3 +57,4 @@ function pauseAlarm() {
4257}
4358
4459window . onload = setup ;
60+
You can’t perform that action at this time.
0 commit comments