-1

suppose i have a view which is fading in and then i call stopAnimation to stop it... at this point is there a way to get the remaining time/duration left like 2000ms or 0 if completed....

below is the example with a fadeIn view. i want to resume the animation but right now when i resume it, it takes another 5 seconds to be completed... i don't want that, when resumed i want it to complete itslef from the point where it stopped.

import React, { useRef } from "react";
import { Animated, Text, View, StyleSheet, Button, SafeAreaView } `from "react-native";`     
const App = () => {
      // fadeAnim will be used as the value for opacity. Initial `Value: 0`
      const fadeAnim = useRef(new Animated.Value(0)).current;
    
      const fadeIn = () => {
        // Will change fadeAnim value to 1 in 5 seconds
        Animated.timing(fadeAnim, {
          toValue: 1,
          duration: 5000
        }).start();
      };
    
      const stop = () => {
        fadeAnim.stopAnimation()
      };
    
      return (
        <SafeAreaView style={styles.container}>
          <Animated.View
            style={[
              styles.fadingContainer,
              {
                // Bind opacity to animated value
                opacity: fadeAnim
              }
            ]}
          >
            <Text style={styles.fadingText}>Fading View!</Text>
          </Animated.View>
          <View style={styles.buttonRow}>
            <Button title="Fade In View" onPress={fadeIn} />
            <Button title="stop" onPress={stop} />
            <Button title="Resume" onPress={fadeIn} />
          </View>
        </SafeAreaView>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center"
      },
      fadingContainer: {
        padding: 20,
        backgroundColor: "powderblue"
      },
      fadingText: {
        fontSize: 28
      },
      buttonRow: {
        flexBasis: 100,
        justifyContent: "space-evenly",
        marginVertical: 16
      }
    });
    
    export default App;
  • Possible duplicate: [link](https://stackoverflow.com/questions/38813491/can-animation-in-react-native-be-paused-and-restarted) – Abe Nov 20 '21 at 23:30
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Nov 25 '21 at 07:08

1 Answers1

0

You can manually calculate remaining time after calling stop():

const valueDifference = toValue - fadeAnim._startingValue;
const remainingTime = (toValue - fadeAnim._value) * (duration / valueDifference);

console.log({ remainingTime });
Tayyab Mazhar
  • 1,560
  • 10
  • 26