Worklet compatible setTimeout and setInterval #3660
-
From within a worklet, is there a way to call another worklet function after a specified delay, or on a regular interval, similar to how My workaround solution (Snack demo here) was to create four worklet functions similar to
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hey! I was looking into the same subject and came across your post. import { useMemo } from 'react';
import { useSharedValue, withTiming } from 'react-native-reanimated';
export const useAnimatedThrottle = <T extends unknown[]>(callback: (...args: T) => void, delay: number) => {
const timeout = useSharedValue(0);
return useMemo(
() =>
(...args: T) => {
'worklet';
if (timeout.value === 0) {
timeout.value = withTiming(1, { duration: delay }, (isDone) => {
if (isDone) {
callback.apply(null, args);
timeout.value = 0;
}
});
}
},
[callback, delay, timeout],
);
}; And a worklet debounce function: import { useMemo } from 'react';
import { cancelAnimation, useSharedValue, withTiming } from 'react-native-reanimated';
export const useAnimatedDebounce = <T extends unknown[]>(callback: (...args: T) => void, delay: number) => {
const timeout = useSharedValue(0);
return useMemo(() => {
const debounced = (...args: T) => {
'worklet';
cancelAnimation(timeout);
timeout.value = 0;
timeout.value = withTiming(1, { duration: delay }, (isDone) => {
if (isDone) {
callback.apply(null, args);
}
});
};
return debounced;
}, [callback, delay, timeout]);
}; I needed to create a scroll back to top button, and your post was extremely helpful! |
Beta Was this translation helpful? Give feedback.
-
Hey! If you want API more similar to the one from JS and don't want to create the timeout with a hook, here is the implementation of mine I made some time ago. You can check it out: I also implemented |
Beta Was this translation helpful? Give feedback.
Hey!
If you want API more similar to the one from JS and don't want to create the timeout with a hook, here is the implementation of mine I made some time ago. You can check it out:
I also implemented
setAnimatedInterval
which is similar to JSsetInterval
.The implementation uses approach similar to what reanimated does while it executes
withTiming
andwithDelay
animations by using therequestAnimationFrame
JS function.