Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ULIB-33] timer 훅 분리 및 수정 #33

Merged
merged 5 commits into from
Sep 19, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat: autoStart 옵션 추가
  • Loading branch information
eunbae0 committed Sep 19, 2023
commit 3c62316b0d3d5bcdfe8a4ac32f745ca17b35fbe3
35 changes: 28 additions & 7 deletions packages/react/src/lib/hooks/useTimer.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,37 @@
import { useCallback, useEffect, useState } from "react";
import { useEffect, useState } from "react";

export const useTimer = (initMin: number, initSec: number) => {
type useTimerProps = {
initMin: number;
initSec: number;
autoStart?: boolean;
};

const addZero = (num: number) => {
if (num < 10) return "0" + num.toString();
else return num.toString();
};

export const useTimer = ({
initMin,
initSec,
autoStart = true,
}: useTimerProps) => {
const [min, setMin] = useState(initMin);
const [sec, setSec] = useState(initSec);
const [isStart, setIsStart] = useState(autoStart);
const [isFinish, setIsFinish] = useState(false);

const addZero = useCallback((num: number) => {
if (num < 10) return "0" + num.toString();
else return num.toString();
}, []);
const startTimer = () => {
setIsStart(true);
};

const resetTimer = () => {
setMin(initMin);
setSec(initSec);
};

useEffect(() => {
if (!isStart) return;
const countDown = setInterval(() => {
if (sec === 0 && min === 0) {
setIsFinish(true);
@@ -26,5 +47,5 @@ export const useTimer = (initMin: number, initSec: number) => {
return () => clearInterval(countDown);
});
const currentTime = addZero(min) + ":" + addZero(sec);
return { currentTime, isFinish };
return { currentTime, isFinish, startTimer, resetTimer };
};