Skip to content

Instantly share code, notes, and snippets.

@ndudar
Created February 14, 2023 21:30
Show Gist options
  • Save ndudar/9e85af97880cbdc4c5fc59ada5c4a424 to your computer and use it in GitHub Desktop.
Save ndudar/9e85af97880cbdc4c5fc59ada5c4a424 to your computer and use it in GitHub Desktop.
useTimer Custom Hook
import { useEffect, useState } from 'react';
//when I use this Hook, I will give it the timer target time in minutes
const useTimer = ({targetTimeMins}) => {
//minutes are converted to milliseconds
const targetTimeMS = targetTimeMins * 60 * 1000
const [timer, setTimer] = useState(targetTimeMS)
useEffect(() => {
let timeRemaining = targetTimeMS
//every 1 second, update the time remaining to be one second less
const interval = setInterval(() => {
setTimer(timeRemaining)
timeRemaining -= 1000
}, 1000)
return () => clearInterval(interval)
}, [targetTimeMS])
//send back the time remaining (ms) to the getReturnedValues function
return getReturnedValues(timer)
}
const getReturnedValues = (timer) => {
//convert the time remaining to minutes and seconds
const minutes = Math.floor(timer / (1000 * 60))
const seconds = Math.floor((timer % (1000 * 60)) / 1000)
//return the minutes and seconds remaining
return [minutes, seconds]
}
export { useTimer }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment