1- // javascript code
1+ // javascript code
2+ let countdown ;
3+ const timerDisplay = document . querySelector ( '.display__time-left' ) ;
4+ const endTime = document . querySelector ( '.display__end-time' ) ;
5+ const buttons = Array . from ( document . querySelectorAll ( '[data-time]' ) ) ;
6+ const alarmClock = document . querySelector ( '.display__alarm-clock' ) ;
7+
8+ function startTimer ( ) {
9+ // stoped the sound
10+ alarmClock . pause ( ) ;
11+ alarmClock . currentTime = 0 ;
12+
13+ const seconds = parseInt ( this . dataset . time ) ;
14+ timer ( seconds ) ;
15+ }
16+
17+ function timer ( seconds ) {
18+ // clear any existing timers
19+ clearInterval ( countdown ) ;
20+
21+ const now = Date . now ( ) ;
22+ const then = ( now + ( seconds * 1000 ) ) ;
23+ displayTimeLeft ( seconds ) ;
24+ displayEndTime ( then ) ;
25+
26+ countdown = setInterval ( ( ) => {
27+ const secondsLeft = Math . round ( ( then - Date . now ( ) ) / 1000 ) ;
28+
29+ // check if we should stop it!
30+ if ( secondsLeft < 0 ) {
31+ // played the sound
32+ alarmClock . currentTime = 0 ;
33+ alarmClock . play ( ) ;
34+
35+ clearInterval ( countdown ) ;
36+ return ;
37+ }
38+
39+ // display it
40+ displayTimeLeft ( secondsLeft ) ;
41+ } , 1000 ) ;
42+ }
43+
44+ function displayTimeLeft ( seconds ) {
45+ const minutes = Math . floor ( seconds / 60 ) ;
46+ const remainderSeconds = ( seconds % 60 ) ;
47+
48+ const display = `${ formatTimer ( minutes ) } :${ formatTimer ( remainderSeconds ) } ` ;
49+
50+ timerDisplay . textContent = display ;
51+ document . title = display ;
52+ }
53+
54+ function displayEndTime ( timestamp ) {
55+ const end = new Date ( timestamp ) ;
56+ const hour = end . getHours ( ) ;
57+ const minutes = end . getMinutes ( ) ;
58+ endTime . textContent = `Be Back At ${ formatTimer ( hour ) } :${ formatTimer ( minutes ) } ` ;
59+ }
60+
61+ function formatTimer ( timer ) {
62+ return `${ timer < 10 ? '0' : '' } ${ timer } ` ;
63+ }
64+
65+ function getCustomForm ( event ) {
66+ // stoped the sound
67+ alarmClock . pause ( ) ;
68+ alarmClock . currentTime = 0 ;
69+
70+ event . preventDefault ( ) ;
71+ const minutes = this . minutes . value ;
72+ this . reset ( ) ;
73+ timer ( minutes * 60 ) ;
74+ }
75+
76+ buttons . map ( button => button . addEventListener ( 'click' , startTimer ) ) ;
77+ document . customForm . addEventListener ( 'submit' , getCustomForm ) ;
0 commit comments