|
| 1 | +import Roact from "@rbxts/roact"; |
| 2 | +import { useBinding, useCallback, useMutable } from "@rbxts/roact-hooked"; |
| 3 | +import { RunService } from "@rbxts/services"; |
| 4 | +import { useEventListener } from "../use-event-listener"; |
| 5 | + |
| 6 | +export interface Timer { |
| 7 | + /** |
| 8 | + * A binding that represents the current value of the timer. |
| 9 | + */ |
| 10 | + readonly value: Roact.Binding<number>; |
| 11 | + /** |
| 12 | + * Starts the timer if it is not already running. |
| 13 | + */ |
| 14 | + readonly start: () => void; |
| 15 | + /** |
| 16 | + * Pauses the timer if it is running. |
| 17 | + */ |
| 18 | + readonly stop: () => void; |
| 19 | + /** |
| 20 | + * Resets the timer to 0. |
| 21 | + */ |
| 22 | + readonly reset: () => void; |
| 23 | + /** |
| 24 | + * Sets the timer to a specific value. |
| 25 | + * @param value The value to set the timer to. |
| 26 | + */ |
| 27 | + readonly set: (value: number) => void; |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * Creates a timer that can be used to track a value over time. |
| 32 | + * @param initialValue The initial value of the timer. |
| 33 | + * @returns A timer object. |
| 34 | + */ |
| 35 | +export function useTimer(initialValue = 0): Timer { |
| 36 | + const [value, setValue] = useBinding(initialValue); |
| 37 | + |
| 38 | + const started = useMutable(true); |
| 39 | + |
| 40 | + useEventListener(RunService.Heartbeat, (deltaTime) => { |
| 41 | + if (started.current) { |
| 42 | + setValue(value.getValue() + deltaTime); |
| 43 | + } |
| 44 | + }); |
| 45 | + |
| 46 | + const start = useCallback(() => { |
| 47 | + started.current = true; |
| 48 | + }, []); |
| 49 | + |
| 50 | + const stop = useCallback(() => { |
| 51 | + started.current = false; |
| 52 | + }, []); |
| 53 | + |
| 54 | + const reset = useCallback(() => { |
| 55 | + setValue(0); |
| 56 | + }, []); |
| 57 | + |
| 58 | + const set = useCallback((value: number) => { |
| 59 | + setValue(value); |
| 60 | + }, []); |
| 61 | + |
| 62 | + return { value, start, stop, reset, set }; |
| 63 | +} |
0 commit comments