From 48e8c85e742c476205f55e44a5f4111bcde44770 Mon Sep 17 00:00:00 2001
From: asketonim
Date: Thu, 2 Jan 2020 14:53:52 +0300
Subject: Implement core timer functionality
---
src/components/Timer/Timer.js | 75 +++++++++++++++++++++++++++++++++++++++++++
src/index.js | 2 ++
2 files changed, 77 insertions(+)
create mode 100644 src/components/Timer/Timer.js
(limited to 'src')
diff --git a/src/components/Timer/Timer.js b/src/components/Timer/Timer.js
new file mode 100644
index 0000000..d0f8ff1
--- /dev/null
+++ b/src/components/Timer/Timer.js
@@ -0,0 +1,75 @@
+import React, { useState, useEffect } from 'react';
+
+import styled from 'styled-components';
+
+const Timer = () => {
+ const [minute, setMinute] = useState(0);
+ const [second, setSecond] = useState(0);
+ const [mill, setMill] = useState(0);
+ const [time, setTime] = useState("00:00:00")
+ const [stopwatchStart, setStopwatchStart] = useState(false);
+ const [stopwatchTime, setStopwatchTime] = useState(0);
+
+ const handleKeyDown = event => {
+ if (event.keyCode === 32){
+
+ if (!stopwatchStart) {
+ setStopwatchTime(Date.now());
+ setStopwatchStart(true);
+ }
+
+ const timeGap = Date.now() - stopwatchTime;
+ setMill(Math.floor((timeGap % 1000) / 10));
+ setSecond(Math.floor(timeGap / 1000));
+ setMinute(Math.floor(timeGap / 60000));
+ setTime(() => {
+ let resultTime = "";
+ if (minute < 10) resultTime += '0';
+ resultTime += minute + ':';
+ if (second < 10) resultTime += '0';
+ resultTime += second + ':';
+ if (mill < 10) resultTime += '0';
+ resultTime += mill;
+ return resultTime;
+ });
+ }
+ }
+
+ const handleKeyUp = event => {
+ if (event.keyCode === 32) {
+ setTime("00:00:00");
+ setMill(0);
+ setSecond(0);
+ setMinute(0);
+ setStopwatchStart(false);
+ setStopwatchTime(0);
+ }
+ }
+
+ useEffect(() => {
+ window.addEventListener("keydown", handleKeyDown);
+ window.addEventListener("keyup", handleKeyUp);
+
+ return () => {
+ window.removeEventListener("keydown", handleKeyDown);
+ window.removeEventListener("keyup", handleKeyUp);
+ };
+ })
+
+ return (
+
+ {time} span>
+
+ );
+
+}
+
+const Root = styled.div`
+ background-color: skyblue;
+ padding: 8px;
+ display: inline-block;
+ font-size: 32px;
+ color: pink;
+`;
+
+export default Timer;
diff --git a/src/index.js b/src/index.js
index 5c657f9..f062952 100644
--- a/src/index.js
+++ b/src/index.js
@@ -5,6 +5,7 @@ import styled from 'styled-components';
import CssBaseline from '@material-ui/core/CssBaseline'
import Header from './components/Header/Header';
+import Timer from './components/Timer/Timer';
const App = () => {
@@ -20,6 +21,7 @@ const App = () => {
This text is rendered outside of Header
component, but
interacting with Header
can influence content of this page!
+
);
};
--
cgit v1.2.3