Skip to content

Instantly share code, notes, and snippets.

@kcabading
Created August 4, 2023 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kcabading/70c98128e88970b4e7b4d16e0854f40b to your computer and use it in GitHub Desktop.
Save kcabading/70c98128e88970b4e7b4d16e0854f40b to your computer and use it in GitHub Desktop.
React hook for using Timer with Milliseconds
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