react-native-reanimated: withTiming / withRepeat slowdown on Android

Description

I’m building a metronome-like app and am using reanimated to animate a box moving to indicate a “tick” of the metronome.

I’ve successfully got my code to make a box bouncing back and forth across the screen in time with my measure. When I hear a click using another metronome app, I see the box hit a side of the view. This works perfectly on iOS, when I sync it with an external click, it never falls out of sync. However on Android it doesn’t take long before it wavers off and the click is nowhere near in sync. That is to say that instead of the box travelling across the screen every 1000ms, it drifts to more.

I’ve boiled down the code to a bare minimum use-case, I think (hope) there’s nothing in there that should be causing a slowdown like this. I’ve tried on all sorts of simulators and the app just seems to drop frames and fail to keep up. The longer it’s open for, the more out of sync it gets. Again, no issues at all on iOS, only Android.

The problem presents itself in dev and production builds, bridgeless and not bridgeless modes too.

Any help would be greatly appreciated 🙏

Steps to reproduce

import { useEffect, useMemo, useState } from 'react'
import { Button, Dimensions, SafeAreaView, View } from 'react-native'
import Reanimated, {
  cancelAnimation,
  Easing,
  useAnimatedStyle,
  useSharedValue,
  withRepeat,
  withTiming,
} from 'react-native-reanimated'

const SCREEN_WIDTH = Dimensions.get('screen').width

export default function App() {
  const [isPlaying, setIsplaying] = useState(false)
  const [bpm, setBpm] = useState(60)
  const intervalTime = useMemo(() => (60 / bpm) * 1000, [bpm]) // Converts BPM to milliseconds per beat

  console.log(`Should hit a wall every ${intervalTime}ms`)
  const bpmMeasureShared = useSharedValue(0)

  useEffect(() => {
    if (!isPlaying) {
      cancelAnimation(bpmMeasureShared)
      bpmMeasureShared.value = 0
    } else {
      bpmMeasureShared.value = withRepeat(
        withTiming(SCREEN_WIDTH - 50, {
          duration: intervalTime,
          easing: Easing.linear,
        }),
        0,
        true
      )
    }
  }, [isPlaying])

  const animatedStyle = useAnimatedStyle(() => {
    return {
      transform: [
        {
          translateX: bpmMeasureShared.value,
        },
      ],
    }
  }, [bpmMeasureShared])

  const togglePlaying = () => {
    setIsplaying(!isPlaying)
  }

  return (
    <SafeAreaView>
      <View style={{ flexDirection: 'row', paddingTop: 50 }}>
        <Button onPress={togglePlaying} title={isPlaying ? 'Stop' : 'Play'} />
      </View>

      <Reanimated.View
        style={[
          { width: 50, height: 50, backgroundColor: 'orange' },
          animatedStyle,
        ]}
      />
    </SafeAreaView>
  )
}

Snack or a link to a repository

See above

Reanimated version

3.15.3

React Native version

0.74.5

Platforms

Android

JavaScript runtime

Hermes

Workflow

Expo Dev Client

Architecture

Fabric (New Architecture)

Build type

None

Device

Android emulator

Device model

No response

Acknowledgements

Yes

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 17 (6 by maintainers)

Most upvoted comments

@kmn988 yes. As I mentioned above, the issue manifesting on Android only was a result of the specific numbers chosen for the reproduction.

I wrote an example implementation of a metronome using useFrameCallback, that doesn’t suffer from this problem:

@bartlomiejbloniarz Thanks so much for taking the time to explain the cause of what I was seeing. Really appreciate it! I’ve just got time to try your solution and it works great. It all makes sense, I just got caught on a track and needed another pair of eyes on it.

@deanhet I wrote an example implementation of a metronome using useFrameCallback, that doesn’t suffer from this problem:

  useFrameCallback((frameTime) => {
    const elapsed = frameTime.timeSinceFirstFrame;

    const bigProgress = elapsed / intervalTime;
    const numOfRounds = Math.floor(bigProgress);

    if (numOfRounds % 2 === 0) {
      progress.value = bigProgress - numOfRounds;
    } else {
      progress.value = 1 - (bigProgress - numOfRounds);
    }
  });