Skip to content

Commit

Permalink
improve timer component (#945)
Browse files Browse the repository at this point in the history
  • Loading branch information
sieu-db authored Aug 27, 2024
1 parent 0d75237 commit 82fa87d
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions packages/core/src/components/Timer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,15 @@ import React, {
useImperativeHandle,
forwardRef,
} from "react";
import { Text, StyleSheet, TextStyle, StyleProp } from "react-native";

interface TimerProps {
import {
Text,
StyleSheet,
TextStyle,
StyleProp,
TextProps,
} from "react-native";

interface TimerProps extends TextProps {
style?: StyleProp<TextStyle>;
initialTime?: number;
updateInterval?: number;
Expand Down Expand Up @@ -35,10 +41,11 @@ const Timer = forwardRef<TimerHandle, TimerProps>(
onTimerEnd,
countDirection = "up",
timerEndTime,
...rest
},
ref
) => {
const defaultInitialTime = countDirection === "up" ? 0 : 100000;
const defaultInitialTime = 0;
const [time, setTime] = useState(initialTime ?? defaultInitialTime);
const timerRef = useRef<NodeJS.Timeout | null>(null);

Expand All @@ -64,7 +71,10 @@ const Timer = forwardRef<TimerHandle, TimerProps>(
// Count down
if (newTime <= 0 && countDirection === "down") {
clearTimer();
onTimerEnd?.();
// Delay the onTimerEnd callback to ensure it triggers after the final time update
setTimeout(() => {
onTimerEnd?.();
}, updateInterval);
return 0;
}
// Count up
Expand All @@ -74,7 +84,10 @@ const Timer = forwardRef<TimerHandle, TimerProps>(
newTime >= timerEndTime
) {
clearTimer();
onTimerEnd?.();
// Delay the onTimerEnd callback to ensure it triggers after the final time update
setTimeout(() => {
onTimerEnd?.();
}, updateInterval);
return timerEndTime;
}

Expand Down Expand Up @@ -123,15 +136,17 @@ const Timer = forwardRef<TimerHandle, TimerProps>(
};

return (
<Text style={[styles.defaultTimerStyle, style]}>{formatTime(time)}</Text>
<Text {...rest} style={[styles.defaultTimerStyle, style]}>
{formatTime(time)}
</Text>
);
}
);

const styles = StyleSheet.create({
defaultTimerStyle: {
fontSize: 24,
textAlign: "center",
textAlign: "left",
},
});

Expand Down

0 comments on commit 82fa87d

Please sign in to comment.