简体   繁体   中英

How to wait for an fadeout function to end?

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?

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
  }
};

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);
        }
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM