Search code examples
javascriptreact-hooksnext.jssetintervalecmascript-2016

How can I offset a 5 minute countdown interval timer by 1 minute, using react JS


I am looking to make a 5-minute interval timer in react JS, that's offset by 1 minute.
The timer I have below lands at 1:00 => 1:05 => 1:10 => 1:15 => 1:20.
I need this to be offset to 1:01 => 1:06 => 1:11 => 1:16 => 1:21.
The timer needs to be in-sync with the Los Angeles time-zone.
Looking for the cleanest es7 code if possible.
I am using NextJS framework.
This is the code I have so far.

  const [timer, setTimer] = useState("")

  const secondPassed = useCallback( () => {
    const cur_date = new Date();
    const minutes = cur_date.getMinutes();
    const seconds = cur_date.getSeconds();
    console.log( (4 - minutes % 5) + ":" + (seconds >= 50 ? "0" : "") + (59 - seconds))
    setTimer( `${(4 - minutes % 5) + ":" + (seconds >= 50 ? "0" : "") + (59 - seconds)}` )
  },[])
  
  useEffect(()=>{
    setInterval(secondPassed, 1000)
  },[])

Solution

  • I offset the starting date by 1 minute.

    const [timer, setTimer] = useState("")
    
      const secondPassed = useCallback( () => {
        const cur_date = new Date( Date.now() - 1000 * 60 );
        const minutes = cur_date.getMinutes();
        const seconds = cur_date.getSeconds();
        console.log( (4 - (minutes % 5)) + ":" + (seconds >= 50 ? "0" : "") + (59 - seconds))
        setTimer( `${(4 - (minutes % 5)) + ":" + (seconds >= 50 ? "0" : "") + (59 - seconds)}` )
      },[])
      
      useEffect(()=>{
        const run = setInterval(secondPassed, 5000)
        return () => clearInterval(run)
      },[])