Advertisement
Guest User

Untitled

a guest
Apr 9th, 2022
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useEffect, useState } from "react";
  2.  
  3. function WaitTimer(props) {
  4.   const appointmentTime = props;
  5.   var textLabel: string = '';
  6.  
  7.   const calculateTime = () => {
  8.  
  9.     const currentTime = new Date().getTime();
  10.     var estimatedTime: number;
  11.     if (appointmentTime > currentTime) {
  12.       // future schedule appointment case
  13.       estimatedTime = appointmentTime - currentTime;
  14.       textLabel = 'Starting: ';
  15.     } else {
  16.       // past scheduled appointment case
  17.       estimatedTime = currentTime + (currentTime - (currentTime + appointmentTime));
  18.       textLabel = 'Waiting: ';
  19.     }
  20.     let timeLeft = {};
  21.     timeLeft = {
  22.       dd: Math.floor(estimatedTime / (1000 * 60 * 60 * 24)),
  23.       hh: Math.floor((estimatedTime / (1000 * 60 * 60)) % 24),
  24.       mm: Math.floor((estimatedTime / 1000 / 60) % 60),
  25.       ss: Math.floor((estimatedTime / 1000) % 60),
  26.     };
  27.     return timeLeft;
  28.   };
  29.   const [timeLeft, setTimeLeft] = useState(calculateTime());
  30.   useEffect(() => {
  31.     setTimeout(() => {
  32.       setTimeLeft(calculateTime());
  33.     }, 1000);
  34.   });
  35.  
  36.   const timerComponents = [];
  37.   Object.keys(timeLeft).forEach((interval) => {
  38.     // adding 00 to null values
  39.     if (!timeLeft[interval]) {
  40.       timerComponents.push(
  41.           <span>{"00"}</span>
  42.       );
  43.     }
  44.     // adding 0 to less than 10 values
  45.      else if(timeLeft[interval] < 10){
  46.       timerComponents.push(
  47.           <span>{'0'}{timeLeft[interval]}</span>
  48.       );
  49.     }
  50.      // adding other values
  51.     else {
  52.       timerComponents.push(
  53.           <span>{timeLeft[interval]}</span>
  54.       );
  55.     }
  56.     // adding colon
  57.       timerComponents.push(
  58.           <span>{":"}</span>
  59.       );
  60.   });
  61.   // removing the last colon after seconds
  62.   timerComponents.pop();
  63.   return (
  64.       <div className="font-bold text-light text-xs" key={textLabel}>
  65.         <div key={props.id}>
  66.           {textLabel} {timerComponents}
  67.         </div>
  68.       </div>
  69.   );
  70. }
  71. export default WaitTimer;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement