@@ -82,9 +82,10 @@ <h1>Pomodoro Timer</h1>
8282 const resetBtn = document . getElementById ( 'resetBtn' ) ;
8383 const durationSelect = document . getElementById ( 'durationSelect' ) ;
8484
85- let timer ;
85+ let startTime ;
8686 let timeLeft = 25 * 60 ; // Default to 25 minutes in seconds
8787 let isRunning = false ;
88+ let duration = 25 * 60 ; // Default duration in seconds
8889
8990 function updateDisplay ( ) {
9091 const minutes = Math . floor ( timeLeft / 60 ) ;
@@ -97,36 +98,46 @@ <h1>Pomodoro Timer</h1>
9798 isRunning = true ;
9899 startBtn . textContent = 'Pause' ;
99100 durationSelect . disabled = true ;
100- timer = setInterval ( ( ) => {
101- timeLeft -- ;
102- updateDisplay ( ) ;
103- if ( timeLeft === 0 ) {
104- clearInterval ( timer ) ;
105- isRunning = false ;
106- startBtn . textContent = 'Start' ;
107- durationSelect . disabled = false ;
108- alert ( 'Pomodoro session complete!' ) ;
109- }
110- } , 1000 ) ;
101+ startTime = Date . now ( ) - ( ( duration - timeLeft ) * 1000 ) ;
102+ requestAnimationFrame ( updateTimer ) ;
111103 } else {
112- clearInterval ( timer ) ;
113104 isRunning = false ;
114105 startBtn . textContent = 'Resume' ;
115106 }
116107 }
117108
109+ function updateTimer ( ) {
110+ if ( isRunning ) {
111+ const elapsedTime = Math . floor ( ( Date . now ( ) - startTime ) / 1000 ) ;
112+ timeLeft = duration - elapsedTime ;
113+
114+ if ( timeLeft <= 0 ) {
115+ timeLeft = 0 ;
116+ isRunning = false ;
117+ startBtn . textContent = 'Start' ;
118+ durationSelect . disabled = false ;
119+ alert ( 'Pomodoro session complete!' ) ;
120+ } else {
121+ requestAnimationFrame ( updateTimer ) ;
122+ }
123+
124+ updateDisplay ( ) ;
125+ }
126+ }
127+
118128 function resetTimer ( ) {
119- clearInterval ( timer ) ;
120129 isRunning = false ;
121- timeLeft = parseInt ( durationSelect . value ) * 60 ;
130+ duration = parseInt ( durationSelect . value ) * 60 ;
131+ timeLeft = duration ;
122132 updateDisplay ( ) ;
123133 startBtn . textContent = 'Start' ;
124134 durationSelect . disabled = false ;
125135 }
126136
127137 function changeDuration ( ) {
128138 if ( ! isRunning ) {
129- timeLeft = parseInt ( durationSelect . value ) * 60 ;
139+ duration = parseInt ( durationSelect . value ) * 60 ;
140+ timeLeft = duration ;
130141 updateDisplay ( ) ;
131142 }
132143 }
0 commit comments