'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?
Solution 1:[1]
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);
}
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FZs |
