1
0

Updated Timer

This commit is contained in:
Christer Warén 2021-01-04 20:02:38 +02:00
parent 1c635092be
commit fe6b12b34e
2 changed files with 28 additions and 13 deletions

View File

@ -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 {

View File

@ -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 (
<div className="timer">
<div className="time">
{seconds}s
{elapsedTime}
</div>
<div className="row">
<button className={`button button-primary button-primary-${isActive ? 'active' : 'inactive'}`} onClick={toggle}>
{isActive ? 'Pause' : 'Start'}
{isActive ? 'Pause' : 'Start'}
</button>
<button className="button" onClick={stop}>
Stop
Stop
</button>
</div>
</div>