How to stop loop animation in React Native?

I have a simple loop animation in my component:

runAnimation() { console.log('run animation'); this.state.angle.setValue(0); Animated.timing(this.state.angle, { toValue: 360, duration: 8000, easing: Easing.linear }).start(() => this.runAnimation()); } ... <Animated.Image style={[ styles.rotate, { transform: [ { rotate: this.state.angle.interpolate({ inputRange: [0, 360], outputRange: ['0deg', '360deg'] })}, ]} ]} source={require('./spinning_ball.png')} /> 

How to stop this animation? For example, when switching to another screen or after a user presses a button.

I tried using this.state.angle.stopAnimation () , but noticed that the run animation is still being saved in the console. Is there any other stop method that I have to call to prevent the callback from starting?

+5
source share
3 answers

Based on my comment in Nguyen Hoang's answer. Here is another way to stop the loop animation if you call this.state.angle.stopAnimation() :

 runAnimation() { this.state.angle.setValue(0); Animated.timing(this.state.angle, { toValue: 360, duration: 8000, easing: Easing.linear }).start((o) => { if(o.finished) { this.runAnimation(); } }); } 
+8
source

You can create a stopAnimation variable to stop the animation whenever you want, only when stopAnimation === false , and then the runAnimation . Example:

 this.state = { stopAnimation: false } runAnimation() { this.state.spinValue.setValue(0); Animated.timing( this.state.spinValue, { toValue: 1, duration: 3000, easing: Easing.linear } ).start( () => { if(this.state.stopAnimation === false) { this.runAnimation(); } }); } 

Therefore, you just need to create a button that calls the this.state = { stopAnimation: true } function to stop the animation.

Example here: https://rnplay.org/apps/Lpmh8A .

+3
source

Set global variable

 let dataloaded = false; 

To stop the animation, redefine the variable (dataloaded) when you want

 componentWillUnmount() { dataloaded = true; } onPress={() => { dataloaded = true; }} 

the final code will look like

 runAnimation() { console.log('run animation'); this.state.angle.setValue(0); Animated.timing(this.state.angle, { toValue: 360, duration: 8000, easing: Easing.linear }) .start(() => { if ( ! dataloaded) { this.runAnimation(); } }) } 
0
source

Source: https://habr.com/ru/post/1264047/


All Articles