skip to Main Content

I created a timer that works like this:

    const targetTime = new Date(props.targetDate).getTime();
    const [currentTime, setCurrentTime] = useState(Date.now());

    const timeBetween = targetTime - currentTime;

    const days = Math.floor(timeBetween / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeBetween % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeBetween % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeBetween % (1000 * 60)) / 1000);

    useEffect(() => {
        const interval = setInterval(() => {
            if (timeBetween < 0) { props.onTimerFinish() }
            setCurrentTime(Date.now());
        }, 1000);
        return () => { clearInterval(interval) };
    }, []);

Then I have my UI that are 4 View‘s displaying days, hours, min, sec.

The onTimerFinish is a Void Function i.e. () => void. I’m checking if (timeBetween < 0) at ever interval so that the moment it goes to negative I’ll know the time is up and I want to trigger the onTimerFinish which is in the parent component of the timer as:

const testDate1 = '2022-11-15T09:30:00.000Z';

<MyCountdownTimer targetDate ={testDate1} onTimerFinish={() => {
     console.log("Hello");
}} />

After the timer runs out it doesn’t call onTimerFinish. I want to refresh the parent component upon finishing the timer.

2

Answers


  1. According to your code, replace if (timeBetween < 0) { props.onTimerFinish() } to if (targetTime - currentTime < 0) { props.onTimerFinish() } may be helpful.

    Login or Signup to reply.
  2. You need to clear the interval when the timer reaches 0.

    const [currentTime, setCurrentTime] = React.useState(Date.now());
    
    const timeBetween = React.useMemo(() => targetTime - currentTime, [currentTime]);
    
    const days = Math.floor(timeBetween / (1000 * 60 * 60 * 24));
    const hours = Math.floor(
    (timeBetween % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    );
    const minutes = Math.floor((timeBetween % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeBetween % (1000 * 60)) / 1000);
    
    React.useEffect(() => {
        timer = setInterval(function () { // declare timer as globally
            setCurrentTime(Date.now());
        }, 1000);
        return () => {
            clearInterval(timer);
        };
    }, []);
    
    React.useEffect(() => {
        if (timer) {
            if (timeBetween <= 1) {
                clearInterval(timer);
                alert("Timer finish");
            }
        }
    }, [timeBetween]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search