Home > Software engineering >  How to wait for an fadeout function to end?
How to wait for an fadeout function to end?

Time:02-26

I would like to change a value when a fadeOut function is over.

I have the following function:

    const fadeOut = (duration: number = 300) => {
        Animated.timing(
            opacity,
            {
                toValue: 0,
                duration,
                useNativeDriver: true
            }
        ).start();
    }

And I call it this way:

    const fadeOutScreen = () => {
        fadeOut(1000);

        // The value would be true when the fadeOut is over
        setHide(true);
    }

But the value is changed before the operation ends.

How can I solve this?

CodePudding user response:

Make it async:

Here are the docs

TS Playground

const fadeOut = (duration: number = 300) => new Promise<boolean>(resolve => {
  Animated.timing(
    opacity,
    {
      toValue: 0,
      duration,
      useNativeDriver: true,
    }
  ).start(({finished}) => resolve(finished));
});

const fadeOutScreen = async () => {
  const finished = await fadeOut(1000);
  if (finished) setHide(true);
  else {
    // animation was interrupted
  }
};

CodePudding user response:

The animation runs asynchronously, but the fadeOutScreen function will continue to execute synchronously after the animation is started.

Animated.start(), however, takes a callback that is called once the animation is finished, so you can do it like this:

const fadeOut = (duration: number = 300, cb?: (boolean) => void) => {
    Animated.timing(
        opacity,
        {
            toValue: 0,
            duration,
            useNativeDriver: true
        }
    ).start(
      //vvvvvvvv--- This tells whether the animation has finished or stopped
      ({finished}) => cb?.(finished)
      //                ^^--- Only call callback if present (new syntax)
    );
}
const fadeOutScreen = () => {
    fadeOut(
        1000, 
        finished => {
            if(finished)
                setHide(true);
        }
    );
}
  • Related