From 6eea30bf1a5cc2b3330f69d2cde0bb6c1536095e Mon Sep 17 00:00:00 2001 From: Tom Miller Date: Mon, 29 Jan 2024 14:17:24 -0500 Subject: [PATCH 01/21] Added useStopwatch hook --- src/hooks/useStopWatch.tsx | 73 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/hooks/useStopWatch.tsx diff --git a/src/hooks/useStopWatch.tsx b/src/hooks/useStopWatch.tsx new file mode 100644 index 0000000..140220c --- /dev/null +++ b/src/hooks/useStopWatch.tsx @@ -0,0 +1,73 @@ +import { useEffect, useMemo, useRef, useState } from "react"; + +export interface Stopwatch { + milliseconds: number; + laps: number[]; + minLapTime: number | null; + maxLapTime: number | null; + isPaused: boolean; + resume: () => void; + pause: () => void; + reset: () => void; + lap: () => void; +} + +export function useStopwatch(): Stopwatch { + const [milliseconds, setMilliseconds] = useState(0); + const [isPaused, setIsPaused] = useState(true); + const [laps, setLaps] = useState([]); + + const lastTime = useRef(Date.now()); + const accumulatedTime = useRef(0); + + function resume() { + if (!isPaused) return; + setIsPaused(false); + lastTime.current = Date.now(); + } + + function pause() { + if (isPaused) return; + setIsPaused(true); + const currentTime = Date.now(); + accumulatedTime.current += currentTime - lastTime.current; + lastTime.current = currentTime; + } + + function reset() { + setIsPaused(true); + lastTime.current = Date.now(); + setMilliseconds(0); + setLaps([]); + accumulatedTime.current = 0; + } + + function lap() { + const lapTime = milliseconds - accumulatedTime.current; + setLaps((laps) => { + return [...laps, lapTime]; + }); + } + + useEffect(() => { + if (isPaused) return; + + const interval = setInterval(() => { + const currentTime = Date.now(); + const timePassed = currentTime - lastTime.current; + setMilliseconds(timePassed+accumulatedTime.current); + }, 10); + + return () => clearInterval(interval); + }, [isPaused]); + + return { + milliseconds, + laps, + isPaused, + resume, + pause, + reset, + lap, + }; +} From cff975f343c65132cf2c3354bf3dbaf83276f885 Mon Sep 17 00:00:00 2001 From: Tom Miller Date: Mon, 29 Jan 2024 14:42:16 -0500 Subject: [PATCH 02/21] Created simple stopwatch button with new hook --- src/StopWatchButton.tsx | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/StopWatchButton.tsx b/src/StopWatchButton.tsx index 8768555..2b23033 100644 --- a/src/StopWatchButton.tsx +++ b/src/StopWatchButton.tsx @@ -1,8 +1,22 @@ -import { View } from 'react-native'; -export default function StopWatchButton() { +import React from 'react'; +import { Button, View } from 'react-native'; + +export default function StopwatchButton({ onResume, onReset, onLap, onPause, isPaused }: { + onReset: () => void; + onLap: () => void; + onPause: () => void; + onResume: () => void; + isPaused: boolean; +}) { + return ( - + +