Skip to content

Instantly share code, notes, and snippets.

@wibed
Created May 19, 2021 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wibed/d5d70e8e2c57da2ca6dcfd3a460c1b55 to your computer and use it in GitHub Desktop.
Save wibed/d5d70e8e2c57da2ca6dcfd3a460c1b55 to your computer and use it in GitHub Desktop.
Rudimentary Timer
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>
);
}
@wibed
Copy link
Author

wibed commented May 19, 2021

improved:

export function useTimer(timeInSeconds) {
  const [timer, setTimer] = useState(null);
  const [timeLeft, setTimeLeft] = useState(timeInSeconds);

  useEffect(() => {
    let timerID = setInterval(() => {
      setTimeLeft((value) => {
        if (value >= 1) {
          return value - 1;
        }
        clearInterval(timerID);
        return value;
      });
    }, 1000);

    return () => clearInterval(timerID);
  }, []);

  return [timer, timeLeft];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment