ソースを参照

timer container done but, has time fault if refresh rate at 10ms

miskson 2 年 前
コミット
5338bc85a0
1 ファイル変更41 行追加4 行削除
  1. 41 4
      hw19-react-jsx-homework/src/App.js

+ 41 - 4
hw19-react-jsx-homework/src/App.js

@@ -1,6 +1,7 @@
 import logo from './logo.svg';
 import './App.css';
 import { useEffect, useState } from 'react';
+import { render } from '@testing-library/react';
 
 const Spoiler = ({header="+", open=true, children}) => {
   let [isOpen=open, setOpen] = useState()
@@ -61,12 +62,10 @@ const PasswordConfirm = ({min=8}) => {
 
 const Timer = ({seconds=10}) => {
   let [time=seconds,  setTime] = useState();
-    //setTimeout(()=> setTime(time - 1), 1000)
     useEffect(() => {
-      const interval = setInterval(()=> setTime(time - 1), 1000)
+      const interval = setInterval(()=> time > 0? setTime(time - 1) : clearInterval(interval), 1000)
       return() => {clearInterval(interval)}
     },[time])
-    //сделать интервал завернуть в юхефект и незабыть клир
   return (
     <strong>
       {Math.floor(((time*1000) / (1000 * 60 * 60)) % 24)} :
@@ -76,6 +75,15 @@ const Timer = ({seconds=10}) => {
   )
 }
 
+const LCD = ({seconds=10}) =>
+  <strong>
+    {Math.floor(((seconds*1000) / (1000 * 60 * 60)) % 24)} :
+    {Math.floor(((seconds*1000) / (1000 * 60)) % 60)} :
+    {Math.floor(((seconds*1000) / 1000) % 60)}
+  </strong>
+
+const SecondsTimer = ({seconds}) => <h2>{seconds}</h2>
+
 const TimerControl = ({hour=0, minute=0, second=0}) => {
   let [hr=hour, setHr] = useState()
   let [min=minute, setMin] = useState()
@@ -117,6 +125,26 @@ const TimerControl = ({hour=0, minute=0, second=0}) => {
   )
 }
 
+const TimerContainer = ({seconds=1800, refresh=100, render:Component}) => {
+  let [timePassed=refresh, setTimePassed] = useState()
+  let [time=seconds*1000, setTime] = useState()
+  useEffect(() => {
+    const interval = setInterval(()=> {
+      if(time > -0) {
+        setTime(seconds*1000 - timePassed)
+        setTimePassed(timePassed + refresh)
+      } else {
+        return clearInterval(interval);
+      }
+    },refresh)
+    return() => clearInterval(interval)
+  }, [refresh, time, timePassed, setTimePassed])
+  
+  return(
+    <Component seconds={time/1000}/>
+  )
+}
+
 
 function App() {
   return (
@@ -131,12 +159,21 @@ function App() {
         <RangeInput min={2}/>
       </Spoiler>
       <br />
+
       <h3>Password Confirm</h3>
       <PasswordConfirm />
+
       <h3>Timer Control</h3>
-      <TimerControl hour={20}/>
+      <TimerControl second={10}/>
+
       <h3>Timer</h3>
       <Timer seconds={7200}/>
+      
+      <h3>Timer Container</h3>
+      <TimerContainer render={SecondsTimer}/>
+      <TimerContainer render={SecondsTimer} seconds={60} refresh={10}/>
+      <TimerContainer render={LCD}/>
+
     </div>
   );
 }