javascriptreact-nativereact-animated

Start animation before loop() reaches end


In my app I have a series of objects, that I animate one by one.

The working code for the animation looks like that so far:

const fields = FIELDS.map( f => ({ scale:useRef( new Animated.Value( 1 ) ).current, offset:useRef( new Animated.Value( 0 ) ).current, f }) )

const animation = Animated.loop(
      Animated.stagger( 180, fields.map( ({ scale, offset }) => Animated.parallel( [
        Animated.sequence( [
          Animated.timing( scale, { ...OPTS, toValue:1.4 } ),
          Animated.timing( scale, { ...OPTS, toValue:1 } ),
        ] ),
        Animated.sequence( [
          Animated.timing( offset, { ...OPTS, toValue:-1.4 } ),
          Animated.timing( offset, { ...OPTS, toValue:0 } ),
        ] ), 
      ] ) ) ),
    { useNativeDriver:true }
)

See the this Snack for the whole code (does NOT work in Web-mode, olny on emulator or real device!)

It looks like this:

enter image description here

The objects are "growing" and "shrinking" from 1 to 6.

Now I want to achieve the following "wave" effect:

When the object (3) is animated, the (1) should be animated as well.

When the object (4) is animated, the (2) should be animated as well.

So, the animation should be performed in 2 (or more) simultaneous waves, shifted by 2 * 180 ms.

How to configure the animation object for that?


Solution

  • It turns out, that a combination of parallel with sequence and delay would do the trick:

      const animation = Animated.loop(
        Animated.parallel( [
          Animated.stagger( DURATION, fields.map( blink ) ),
          Animated.sequence( [
            Animated.delay( DURATION * ( fields.length - 1 ) / 2 ),
            Animated.stagger( DURATION, fields.map( blink ) ),
          ] ),
        ] ),
        { useNativeDriver:true }
      )
    
    
    

    See the updated Snack