Skip to content

Commit

Permalink
fixup! fix(suite): use Date to prevent long timing drift in useTimer
Browse files Browse the repository at this point in the history
  • Loading branch information
adderpositive committed Oct 25, 2024
1 parent 17280e5 commit 2a93be0
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 deletions packages/react-utils/src/hooks/useTimer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, useRef } from 'react';

export interface Timer {
timeSpend: {
Expand All @@ -13,36 +13,37 @@ export interface Timer {
}

export const useTimer = (): Timer => {
const [timestamp, setTimestamp] = useState(Date.now());
const [timeSpend, setTimeSpend] = useState(0);
const [isLoading, setIsLoading] = useState(false);
const [isStopped, setIsStopped] = useState(false);
const [resetCount, setResetCount] = useState(0);
const intervalRef = useRef<NodeJS.Timeout | null>(null);

useEffect(() => {
if (isStopped || isLoading) {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}

return;
}

const interval = setInterval(() => {
const dateNow = Date.now();

if (timestamp + 1000 <= dateNow) {
setTimestamp(timestamp + 1000);
setTimeSpend(prevTime => prevTime + 1000);
}
}, 10);
intervalRef.current = setInterval(() => {
setTimeSpend(prevTime => prevTime + 1000);
}, 1000);

return () => {
clearInterval(interval);
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
};
}, [isLoading, isStopped, timestamp]);
}, [isLoading, isStopped]);

const reset = () => {
setIsLoading(false);
setResetCount(resetCount + 1);
setResetCount(prev => prev + 1);
setTimeSpend(0);
setTimestamp(Date.now());
setIsStopped(false);
};

Expand All @@ -52,7 +53,6 @@ export const useTimer = (): Timer => {

const loading = () => {
setTimeSpend(0);
setTimestamp(Date.now());
setIsLoading(true);
setIsStopped(false);
};
Expand Down

0 comments on commit 2a93be0

Please sign in to comment.