aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/app/components/Gaming/Score.tsx
blob: b4a415c4536ca580f79e7520af8282f834bb4a05 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { useEffect, useState } from "react";

type Props = {
	status: string | null;
	score: number | null;
};

export default function Score({ status, score }: Props) {
	const [displayScore, setDisplayScore] = useState(score);

	useEffect(() => {
		let intervalId = null;

		if (status === "running") {
			intervalId = setInterval(() => {
				const maxValue = Math.pow(10, String(score ?? 100).length) - 1;
				const minValue = Math.pow(10, String(score ?? 100).length - 1);
				const randomValue =
					Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue;
				setDisplayScore(randomValue);
			}, 50);
		} else {
			setDisplayScore(score);
		}

		return () => {
			if (intervalId) {
				clearInterval(intervalId);
			}
		};
	}, [status, score]);

	return (
		<span className={status === "running" ? "animate-pulse" : ""}>
			{displayScore}
		</span>
	);
}