ryzhak
ryzhak

Reputation: 405

How to prevent setInterval in react native from blocking running animation?

I have a react native application. There are 2 components: tickets and ticket details. In the "tickets" component there is a list of tickets. When a user clicks on a single ticket the "ticket details" component is shown. In the "tickets" component there is the setInterval which retrieves tickets from the server every 10 seconds. In the "ticket details" component there is the animated progress bar(using react native Animated module).

Issue: every 10 seconds animation in "ticket details" component freezes. How to solve?

I guess that is because of setInterval blocks main UI thread.

I tried: - https://facebook.github.io/react-native/docs/interactionmanager.html but I didn't even manage to call runAfterInteractions on my RN 0.58.

The next thing that comes to mind is https://github.com/joltup/react-native-threads. But it is a native module with some scary issues like "memory leak" and additional build instructions so I don't really want to use it.

I think I miss a way easier method to solve this issue.

This is how I get tickets in the "tickets" component. getTickets is a redux action.

componentDidMount() {
this.timer = setInterval(() => {
    const {getTickets} = this.props;
    getTickets();
 }, 10000);
}

This is the animated progress bar from the "ticket details" component. I doubt that it was useful concerning this issue. Just for reference.

<ProgressBarAnimated 
    value={100} 
    barAnimationDuration={progressBarAnimationDuration} 
    width={progressBarWidth}
    borderWidth={0}
    backgroundColor='#1d1e1f'
    height={8}
    borderRadius={0} />

I expect setInterval not to freeze progress bar animation.

Once again how I see the process:

  1. progress bar animation is running

  2. every 10th-second setInterval performs HTTP request and blocks main UI thread(with progress bar animation) for ~2 seconds

  3. when the request is done animation is back to normal

Upvotes: 2

Views: 2274

Answers (1)

ryzhak
ryzhak

Reputation: 405

The animation was blocked because it was running in JS thread instead of UI thread.

You should run animation in the UI thread via https://facebook.github.io/react-native/docs/animated with option useNativeDriver: true. With this option animation is smooth.

Also notice that if you use PanResponder + Animated then useNativeDriver option does not work. You can go with https://github.com/wix/react-native-interactable. I've tried it and all animations on touches are running in the UI thread so animation is not blocked.

Upvotes: 1

Related Questions