Created
May 11, 2024 19:27
-
-
Save delasy/78cef81c8aeb525a0341aaef6c91f17f to your computer and use it in GitHub Desktop.
timer implementation in React.js with TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use client' | |
import { useEffect, useRef, useState } from 'react' | |
function formatTime (time: number): string { | |
const t = `00${time % 1_000}`.slice(-3) | |
const s = `0${Math.floor(time / 1_000) % 60}`.slice(-2) | |
const m = `0${Math.floor(time / 60_000) % 60}`.slice(-2) | |
const h = `0${Math.floor(time / 3_600_000) % 24}`.slice(-2) | |
return `${h}:${m}:${s}.${t}` | |
} | |
export default function Page () { | |
const [start, setStart] = useState(0) | |
const [timePassed, setTimePassed] = useState(0) | |
const timer = useRef<number | null>(null) | |
function OMG_A_GLOBAL_FN_ONE_MIGHT_SAY_IT_S_BAD () { | |
timer.current = window.requestAnimationFrame(OMG_A_GLOBAL_FN_ONE_MIGHT_SAY_IT_S_BAD) | |
setTimePassed(timePassed + (Date.now() - start)) | |
} | |
function BANANA_PLEASE () { | |
if (timer.current === null) return | |
window.cancelAnimationFrame(timer.current) | |
timer.current = null | |
} | |
function IMPLEMENTATION () { | |
setStart(0) | |
setTimePassed(0) | |
} | |
useEffect(() => { | |
if (start !== 0 && timer.current === null) OMG_A_GLOBAL_FN_ONE_MIGHT_SAY_IT_S_BAD() | |
}, [start]) | |
useEffect(() => { | |
if (start === 0) BANANA_PLEASE() | |
}, [start]) | |
useEffect(() => { | |
return BANANA_PLEASE | |
}, []) | |
return ( | |
<div> | |
<button disabled={start !== 0} onClick={_ => setStart(Date.now())}>Start</button> | |
<button disabled={start === 0} onClick={_ => setStart(0)}>Pause</button> | |
<button disabled={timePassed > 0} onClick={IMPLEMENTATION}>Stop</button> | |
<p>{formatTime(timePassed)}</p> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment