11let tripEnded = true ;
2- let tripTimerRunning = false ;
2+ let tripTimerCode = null ;
33let ratedTripsList = [ ] ;
44let finishedTripsList = [ ] ;
55let tripBeingRated = false ;
@@ -351,6 +351,8 @@ async function startBikeTrip(event, bikeName) {
351351 // hide bike list if it is showing
352352 if ( document . querySelector ( "#bikeMenu" ) ) document . querySelector ( "#bikeMenu" ) . remove ( ) ;
353353
354+ const oldTrip = document . getElementById ( "tripOverlay" ) ;
355+ if ( oldTrip ) oldTrip . remove ( ) ; // remove the trip overlay if it is showing
354356 // show the trip overlay
355357 appendElementToBodyFromHTML (
356358 `
@@ -371,12 +373,17 @@ async function startBikeTrip(event, bikeName) {
371373
372374 // start the trip timer
373375 tripEnded = false ;
374- tripTimer ( Date . now ( ) ) ;
376+ tripTimer ( Date . now ( ) , true ) ;
375377 } , 3000 ) ;
376378 }
377379}
378380
379- async function tripTimer ( startTime ) {
381+ async function tripTimer ( startTime , isStarting ) {
382+ // Only need to clear the previous trip if this trip is starting
383+ if ( tripTimerCode && isStarting ) {
384+ clearTimeout ( tripTimerCode ) ; // clear the previous timer if it exists
385+ tripTimerCode = null ;
386+ }
380387 // Update only is trip has not ended, and websocket is connected
381388 if ( ! tripEnded && ws ?. readyState === WebSocket . OPEN ) {
382389 // Calculate elapsed time
@@ -405,14 +412,13 @@ async function tripTimer(startTime) {
405412 }
406413 }
407414 }
408- tripTimerRunning = true ;
409- setTimeout ( ( ) => tripTimer ( startTime ) , 1000 ) ;
415+ tripTimerCode = setTimeout ( ( ) => tripTimer ( startTime ) , 1000 ) ;
410416 } else if ( ws ?. readyState !== WebSocket . OPEN ) {
411417 console . log ( "WebSocket has disconnected..." ) ;
412418 setTimeout ( ( ) => tripTimer ( startTime ) , 1000 ) ;
413419 } else {
414420 console . log ( "Trip has ended..." ) ;
415- tripTimerRunning = false ;
421+ tripTimerCode = null ;
416422
417423 // Hide trip overlay if it is showing
418424 if ( document . querySelector ( "#tripOverlay" ) ) document . querySelector ( "#tripOverlay" ) . remove ( ) ;
0 commit comments