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

[Fix] 페이지 벗어나 있으면 타이머 안 움직이는 에러 해결 #311

Merged
merged 2 commits into from
Jul 30, 2024
Merged
Changes from all commits
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
45 changes: 27 additions & 18 deletions src/common/components/Input/components/Timer/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import { differenceInSeconds } from 'date-fns';
import { useEffect, useState } from 'react';

import { timer } from './style.css';
import { TimerProps } from './types';
Expand All @@ -8,29 +9,37 @@ const INITIAL_TIME = 300;

// TextBox 내부 타이머
const Timer = ({ isActive, onResetTimer }: TimerProps) => {
const [seconds, setSeconds] = useState(INITIAL_TIME);
const timerRef = useRef<NodeJS.Timeout | null>(null);
const clearTimer = () => {
setSeconds(INITIAL_TIME);
timerRef.current && clearInterval(timerRef.current);
};
const [seconds, setSeconds] = useState(INITIAL_TIME - 1);

useEffect(() => {
let timeout: NodeJS.Timeout | null = null;

if (isActive) {
timerRef.current = setInterval(() => {
setSeconds((prev) => {
if (prev <= 1) {
onResetTimer();
clearTimer();
return INITIAL_TIME;
}
return prev - 1;
});
}, 1000);
const initialDate = new Date();
const ExpiryTime = new Date(initialDate.getTime() + INITIAL_TIME * 1000);

const tick = () => {
const now = new Date();
const diffInSeconds = differenceInSeconds(ExpiryTime, now);

if (diffInSeconds > 0) {
setSeconds(diffInSeconds === INITIAL_TIME ? INITIAL_TIME - 1 : diffInSeconds);
timeout = setTimeout(tick, 1000 - (now.getTime() % 1000));
} else {
onResetTimer();
setSeconds(INITIAL_TIME - 1);
}
};

tick();
} else {
setSeconds(INITIAL_TIME - 1);
}

return () => {
clearTimer();
if (timeout) {
clearTimeout(timeout);
}
};
}, [isActive, onResetTimer]);

Expand Down