Home > OS >  How to stop animate (animation) in React
How to stop animate (animation) in React

Time:10-09

How can we stop animation onPress. Currently I can start the animate onPress. I can also stop the animate onPress. The problem is that when I press button to stop animate it stops the animation in the middle of the animation. I am hoping to have it stop the animation onPress after the animation runs it course

EXAMPLE: opacity has text blinking. When I press the stop button the text opacity may be at 40%. I would like it to only stop once it reach 0%

const Animated_2 = () => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(animation, {
          toValue: 0,
          duration: props.duration,
          useNativeDriver: false,
        }),

        Animated.timing(animation, {
          toValue: 1,
          duration: props.duration,
          useNativeDriver: false,
        }),
      ]),
      {
        iterations: props.repeat_count,
      },
    ).start();
  };

  const stop = () => {
    Animated.timing(animation).stop();
  };

CodePudding user response:

You can do the looping yourself to have more control over the animation. like so:

const [stopRequested, setStopRequested] = useState(false);
const [remainingLoops, setRemainingLoops] = useState(0);

function startAnimation() {
  setRemainingLoops(props.repeat_count);
  nextLoop();
}

function nextLoop() {
  Animated.timing(animation, {
    toValue: 0,
    duration: props.duration,
    useNativeDriver: false,
  }).start(() => {
    if (stopRequested) {
      setStopRequested(false);
      return;
    }
    Animated.timing(animation, {
      toValue: 1,
      duration: props.duration,
      useNativeDriver: false,
    }).start(() => {
      if (remainingLoops !== 0) {
        setRemainingLoops(remainingLoops => remainingLoops - 1);
        nextLoop();
      }
    });
  });  
}

function stopAnimation() {
  setStopRequested(true);
}

CodePudding user response:

add a listener to the animation using addListener(). You can get the value of your animation once it reaches a key. Use a state to detect when a user has clicked on stop and check it in the listener to stop. To make sure you have stopped at the value you wanted to, you can reset it to a certain offset.

  • Related