1- function setAlarm ( ) { }
1+ const input = document . getElementById ( "alarmSet" ) ;
2+ const timeDisplay = document . querySelector ( "span" ) ;
3+
4+ let alarmInterval = null ;
5+
6+ function setAlarm ( ) {
7+ // sanitize input: convert to number, floor to integer seconds, clamp to >= 0
8+ let timeInput = Math . floor ( Number ( input . value ) || 0 ) ;
9+ if ( timeInput < 0 ) timeInput = 0 ;
10+
11+ // clear any existing interval so multiple clicks don't create multiple timers
12+ if ( alarmInterval ) {
13+ clearInterval ( alarmInterval ) ;
14+ alarmInterval = null ;
15+ }
16+
17+ // handle negative input explicitly
18+ const rawValue = Number ( input . value ) ;
19+ if ( rawValue < 0 ) {
20+ timeDisplay . textContent = "Invalid value" ;
21+ return ;
22+ }
23+
24+ let minutes = Math . floor ( timeInput / 60 ) ;
25+ let seconds = timeInput % 60 ;
26+
27+ minutes = minutes . toString ( ) . padStart ( 2 , "0" ) ;
28+ seconds = seconds . toString ( ) . padStart ( 2 , "0" ) ;
29+ timeDisplay . textContent = `${ minutes } :${ seconds } ` ;
30+
31+ // if the input is 0, trigger the alarm immediately
32+ if ( timeInput <= 0 ) {
33+ playAlarm ( ) ;
34+ return ;
35+ }
36+
37+ alarmInterval = setInterval ( ( ) => {
38+ timeInput -- ;
39+ let remainingMinutes = Math . floor ( timeInput / 60 ) ;
40+ let remainingSeconds = timeInput % 60 ;
41+ remainingMinutes = remainingMinutes . toString ( ) . padStart ( 2 , "0" ) ;
42+ remainingSeconds = remainingSeconds . toString ( ) . padStart ( 2 , "0" ) ;
43+ timeDisplay . textContent = `${ remainingMinutes } :${ remainingSeconds } ` ;
44+ if ( timeInput <= 0 ) {
45+ playAlarm ( ) ;
46+ clearInterval ( alarmInterval ) ;
47+ alarmInterval = null ;
48+ }
49+ } , 1000 ) ;
50+ }
251
352// DO NOT EDIT BELOW HERE
453
@@ -20,6 +69,11 @@ function playAlarm() {
2069
2170function pauseAlarm ( ) {
2271 audio . pause ( ) ;
72+ audio . currentTime = 0 ;
73+ if ( alarmInterval ) {
74+ clearInterval ( alarmInterval ) ;
75+ alarmInterval = null ;
76+ }
2377}
2478
2579window . onload = setup ;
0 commit comments