Created
May 19, 2021 04:43
-
-
Save wibed/d5d70e8e2c57da2ca6dcfd3a460c1b55 to your computer and use it in GitHub Desktop.
Rudimentary Timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "./styles.css"; | |
import { useState, useEffect } from "react"; | |
function useTimer(timeInSeconds) { | |
const [timer, setTimer] = useState(0); | |
const [timeLeft, setTimeLeft] = useState(timeInSeconds); | |
if (typeof timer !== "number") { | |
return console.log("useTimer first argument must be a number"); | |
} | |
useEffect(() => { | |
setTimer( | |
setTimeout(() => { | |
timeLeft >= 1 ? setTimeLeft(timeLeft - 1) : console.log("end"); | |
}, 1000) | |
); | |
}, [timeLeft]); | |
return [timer, timeLeft]; | |
} | |
export default function App() { | |
const timer = useTimer(10); | |
console.log(timer); | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<h2>Start editing to see some magic happen!</h2> | |
<p>{timer[1]}</p> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
improved: