Home > Enterprise >  React-Native: Function is not being triggered after timer finishes running
React-Native: Function is not being triggered after timer finishes running

Time:11-15

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.

CodePudding user response:

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

CodePudding user response:

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(() => {
    const interval = setInterval(() => {
        if (timeBetween <= 0) {
            clearInterval(interval) // clear the interval to stop timer
            alert("Timer finish")
        } else {
            setCurrentTime(Date.now());
        }
    }, 1000);
    return () => { clearInterval(interval) };
}, [timeBetween]);
  • Related