Coming soon!

React Native’s Animated.loop: Invoking A Callback Whenever An Iteration Finishes

  • react-native-animation
  • react-native
  • javascript

By Benjamin Todts · 3/26/2019 7:18:58 PM (Original Post)

React Native’s Animated.loop function is great to continuously run animations, but it lacks one feature: invoking a callback whenever an iteration is finished.

pexels.com

Looping Animations

With React Native’s Animated.loop function, you can continuously run a given Animation. Consider the following snippet:

Because of Animated.loop, the Animated.sequence will continuously repeat.
Inside the sequence, we wait for 3 seconds using Animated.delay and then perform a transition of the this.state.width property to value 400, over a course of 2 seconds.

Animated.loop also takes a configuration object, in thise case: { iterations: 10 }, indicating that (you guessed it): the animations should loop 10 times.
If you don’t specify this property, the animations will loop indefinitely.

What about the .start() callback?

But what if we want to invoke a callback whenever an iteration is finished?
The start() function accepts a callback that will be invoked, but only when all iterations are finished. In our example, it would invoked after 10 iterations.

If you don’t specify a number of iterations, the callback will never be invoked.

The Workaround

Fortunately, we can use this callback parameter in a creative manner:

Instead of using Animated.loop , we’ve wrapped the Animated.sequence in a function, which we invoke when the callback from Animated.sequence(...).start() is invoked, thus looping endlessly.

You could still limit the number of iterations by using a property on this.state.

👏 Thanks for reading! 👏


  • react-native-animation
  • react-native
  • javascript

By Benjamin Todts · 3/26/2019 7:18:58 PM (Original Post)

Share this blogpost

Looking for talent?

Fill in the form below and we’ll get back to you as soon as possible.

Oops. You seem to have written your full name in invisible ink. Please enter it so we can read it. Oops. You seem to have written your company in invisible ink. Please enter it so we can read it. It seems your e-mail doesn’t exist. Please enter a real one so we can contact you. Oops. You seem to have written your telephone in invisible ink. Please enter it so we can read it.