-
Hello! How to create a timer that runs with Reanimated?
Can i use this in worklets or using animations? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hey! There is no out-of-the-box solution provided by the reanimated library but you can build the one yourself. I used this approach and it seemed to work fine for my needs: type AnimatedTimer = {
set: (callback: () => void, duration: number) => void;
clear: () => void;
};
export function useAnimatedTimer(): AnimatedTimer {
'worklet';
const value = useSharedValue(0);
return useMemo(
() => ({
clear: () => {
'worklet';
value.value = 0;
},
set: (callback: () => void, duration: number) => {
'worklet';
value.value = withTiming(1, { duration }, completed => {
if (completed) {
value.value = 0;
callback();
}
});
}
}),
[value]
);
} Because both methods ( const myAnimatedTimer = useAnimatedTimer()
// For example, use it in the useAnimatedReaction callback
useAnimatedReaction(
() => { /* prepare values */ },
() => {
/* react to value changes */
// Set the timer
myAnimatedTimer.set(() => {
// Update shared value or do something else
}, 1000)
}) |
Beta Was this translation helpful? Give feedback.
-
I found better solution than the one I proposed above. Here is a link to the comment where I pasted implementations with API very similar to the JS |
Beta Was this translation helpful? Give feedback.
I found better solution than the one I proposed above. Here is a link to the comment where I pasted implementations with API very similar to the JS
setTimeout
andsetInterval
API.