menaka
menaka

Reputation: 1068

How to stop react-spring looping animation

I have a pulsing simple Timer. I want to stop pulsing animation when the time hit "0". I am kinda new to the react-spring if anyone know how to do this please help.

const Timer = ({time = 0}) => {
    const [timer, setTimer] = useState(time);

    const props = useSpring({
        config: {duration: 1000},
        from: { scale: 1 },
        to: {scale: 1.1},
        loop: timer > 0,
    });

    useEffect(() => {
        if (!timer) return;

        const intervalId = setInterval(() => {
            setTimer(timer - 1);
        }, 1000);

        return () => clearInterval(intervalId);
    }, [timer])

    return (<animated.div style={props} className={'timer-main'}>
        { timer }
    </animated.div>)
}

Upvotes: 0

Views: 1090

Answers (2)

birkan alp yaman
birkan alp yaman

Reputation: 26

const Timer = ({time = 0}) => {
const [timer, setTimer] = useState(time);
const [isCancel, setIsCancel] = useState(false);

const props = useSpring({
    config: {duration: 1000},
    from: { scale: 1 },
    to: {scale: 1.1},
    loop: timer > 0,
    cancel: isCancel
});

useEffect(() => {
    if (!timer) return;

    const intervalId = setInterval(() => {
        const newTime = timer - 1;

        setTimer(newTime);
        
        if(newTime === 0){
          setIsCancel(true)
        }
    }, 1000);

    return () => clearInterval(intervalId);
}, [timer])

return (<animated.div style={props} className={'timer-main'}>
    { timer }
</animated.div>)
}

There is cancel property in spring and it stops animation with boolean.

Upvotes: 1

menaka
menaka

Reputation: 1068

I fixed it with a "not so ideal" solution, still open to a better one.

return (<animated.div style={timer > 0 ? props : {}} className={'timer-main'}>
        { timer }
    </animated.div>)

Upvotes: 1

Related Questions