From fe6b12b34efcbe78667184ab485930d91b527826 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christer=20War=C3=A9n?= Date: Mon, 4 Jan 2021 20:02:38 +0200 Subject: [PATCH] Updated Timer --- src/Timer.css | 5 ++--- src/Timer.js | 36 ++++++++++++++++++++++++++---------- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/src/Timer.css b/src/Timer.css index fcaeec0..151ab66 100644 --- a/src/Timer.css +++ b/src/Timer.css @@ -1,17 +1,16 @@ -.app { +.timer { text-align: center; - background-color: #282c34; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; + flex: 1; } .time { font-size: 3rem; - padding: 2rem; } .button { diff --git a/src/Timer.js b/src/Timer.js index 768b500..c4ce1fd 100644 --- a/src/Timer.js +++ b/src/Timer.js @@ -1,19 +1,23 @@ -// I used code as basis to this Timer +// Timer is based on these with changes + // Build a React Timer Component Using Hooks by James King // https://upmostly.com/tutorials/build-a-react-timer-component-using-hooks import React, { useState, useEffect } from 'react'; const Timer = () => { - const [seconds, setSeconds] = useState(0); + const [startTime, setStartTime] = useState(0); + const [elapsedTime, setElapsedTime] = useState("0.0"); const [isActive, setIsActive] = useState(false); function toggle() { + setStartTime(new Date()); setIsActive(!isActive); } function stop() { - setSeconds(0); + setStartTime(0); + setElapsedTime("0.0"); setIsActive(false); } @@ -21,25 +25,37 @@ const Timer = () => { let interval = null; if (isActive) { interval = setInterval(() => { - setSeconds(seconds => seconds + 1); - }, 1000); - } else if (!isActive && seconds !== 0) { + let epochElapsedTime = new Date() - startTime; + + let elapsedTime = { + minutes: new Date(epochElapsedTime).getMinutes(), + seconds: new Date(epochElapsedTime).getSeconds(), + milliseconds: new Date(epochElapsedTime).getMilliseconds() + }; + + if(elapsedTime.minutes !== 0){ + setElapsedTime(elapsedTime.minutes + ":" + elapsedTime.seconds + "." + elapsedTime.milliseconds); + } else { + setElapsedTime(elapsedTime.seconds + "." + elapsedTime.milliseconds); + } + }, 10); + } else if (!isActive && startTime !== 0 && elapsedTime !== "0.0") { clearInterval(interval); } return () => clearInterval(interval); - }, [isActive, seconds]); + }, [isActive, startTime, elapsedTime]); return (
- {seconds}s + {elapsedTime}