简体   繁体   中英

How to not let a timer stop in nextJS when idle

Basically, I created a simple timer app with Next

https://sitstandtimer.vercel.app/

and I want it to just stay counting even if I'm not on the browser window. When I go to another window for about 5 minutes it stops counting, which is odd behavior. Here's the code for the Timer:

 const useTimer = (initialState = 0) => { const [timer, setTimer] = useState(initialState) const [isActive, setIsActive] = useState(false) const [isPaused, setIsPaused] = useState(false) const countRef = useRef(null) const handleStart = () => { setIsActive(true) setIsPaused(true) countRef.current = setInterval(() => { setTimer((timer) => timer + 1) }, 1000) } const handlePause = () => { clearInterval(countRef.current) setIsPaused(false) } const handleResume = () => { setIsPaused(true) countRef.current = setInterval(() => { setTimer((timer) => timer + 1) }, 1000) } const handleReset = () => { clearInterval(countRef.current) setIsActive(false) setIsPaused(false) setTimer(0) } return { timer, isActive, isPaused, handleStart, handlePause, handleResume, handleReset, setTimer } }

As already answered in the comment. Setting time elapsed instead of adding 1 is usually a better solution because browsers can slow down or disable intervals in the background.

const useTimer = (initialTime = 0) => {
    const [startTime, setStartTime) = useState(0);
    const [timer, setTimer] = useState(initialState)
    const [isActive, setIsActive] = useState(false)
    const [isPaused, setIsPaused] = useState(false)
    const countRef = useRef(null)

    const startInterval = () => setInterval(() => {
        setTimer((Date.now() - startTime) / 1000)
      }, 1000)
    }
  
    const handleStart = () => {
      setStartTime(Date.now())
      setIsActive(true)
      setIsPaused(true)
      countRef.current = startInterval()
  
    const handlePause = () => {
      clearInterval(countRef.current)
      setIsPaused(false)
    }
  
    const handleResume = () => {
      setIsPaused(true)
      countRef.current = startInterval()
    }
  
    const handleReset = () => {
      clearInterval(countRef.current)
      setIsActive(false)
      setIsPaused(false)
      setTimer(0)
    }
  
    return { timer, isActive, isPaused, handleStart, handlePause, handleResume, handleReset, setTimer }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM