I want to create a timer or stopwatch for my video player project to count views, for that I want a simple stopwatch to enter my logic for the view counter.
I tried creating the stopwatch and timer using setInterval but that didn't work as I was expecting.
CodePudding user response:
you can make a customHook for timer
import React, { useEffect, useState } from "react";
const useTimer = (delay) => {
const [state, setState] = useState(0)
const [stop, isSetStop] = useState(false)
useEffect(() => {
if (stop) return
console.log("TIMER RUNNING=>>>>>>>>>>>");
setTimeout(() => {
setState((prev => prev 1))
}, delay)
}, [state])
return [state, () => isSetStop(true)]
}
export default useTimer
use it like this
const [time, stopTime] = useTimer(1000)
you can reverse it and it will be stopwatch and you can call stopTime method to stop it or you can put condition in useEffect of hook
useEffect(() => {
if (stop || state >= 60 ) return
console.log("TIMER RUNNING=>>>>>>>>>>>");
setTimeout(() => {
setState((prev => prev 1))
}, delay)
}, [state])