Created
August 4, 2023 16:51
-
-
Save kcabading/70c98128e88970b4e7b4d16e0854f40b to your computer and use it in GitHub Desktop.
React hook for using Timer with Milliseconds
This file contains hidden or 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
import { useState, useRef } from "react"; | |
const Timer = ( initial: number, ascending: boolean) => { | |
const [ms, setMs] = useState(initial * 100) | |
const [timesUp, setTimesUp] = useState<boolean>(false) | |
const intervalRef = useRef<number>() | |
function convertMSTimeToString (ms: number){ | |
const minutes = String(Math.floor( ms / 100 / 60)).padStart(2, '0') | |
const seconds = String(Math.floor( (ms / 100) % 60 )).padStart(2, '0') | |
const milliseconds = String(Math.floor(ms % 100)).padStart(2, '0') | |
const timerString = `${minutes}:${seconds}:${milliseconds}` | |
return { | |
minutes, | |
seconds, | |
milliseconds, | |
timerString | |
} | |
} | |
function stopTimer() { | |
window.clearInterval(intervalRef.current) | |
} | |
function startTimer() { | |
let intervalId = window.setInterval(() => { | |
setMs( (prev) => { | |
if (!ascending && prev === 0) { | |
stopTimer() | |
return prev | |
} else { | |
return ascending ? prev + 1 : prev - 1 | |
} | |
}) | |
}, 10) | |
intervalRef.current = intervalId | |
} | |
function resetTimer() { | |
setMs(initial) | |
} | |
let { minutes, seconds, milliseconds, timerString} = convertMSTimeToString(ms) | |
return { minutes, seconds, milliseconds, timerString, timesUp, stopTimer, startTimer, resetTimer } | |
} | |
export default Timer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment