Skip to content

fix: show new timing animations after a main-thread stall - #11769

Draft
bartlomiejbloniarz wants to merge 2 commits into
@bartlomiejbloniarz/animation-set-start-timefrom
@bartlomiejbloniarz/frame-start-after-stalls
Draft

bartlomiejbloniarz wants to merge 2 commits into
@bartlomiejbloniarz/animation-set-start-timefrom
@bartlomiejbloniarz/frame-start-after-stalls

Conversation

@bartlomiejbloniarz

@bartlomiejbloniarz bartlomiejbloniarz commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Note

This pull request was authored by AI on behalf of @bartlomiejbloniarz.

Summary

A 600 ms main-thread stall can make a new 400 ms shared-value animation jump to its target. On iOS this can happen even when the assignment reaches the UI thread after the stall. The first display-link callback can carry a timestamp from before the stall, which moves the timing animation's clock backward.

The Worklets change advances a delayed iOS timestamp by whole vsync intervals before applying simulator slow-animation scaling. The Reanimated commit is a separate experiment for fresh withTiming animations assigned to a shared value or returned from useAnimatedStyle. It resets the clock when the first frame is at least 33 ms late on both the animation and wall clocks. Once a frame has run, the animation catches up after stalls using its original clock.

Frame timelines

Before is #11603. After includes both changes in this draft. The Start marker shows when the assignment reaches the UI thread. Queued starts are marked at unblock.

iOS frame timelines, Before and After

Android frame timelines, Before and After

Test plan

  • On iOS, the timestamp correction restored the queued animation in all three trials. In the baseline the first callback's timestamp was about 585 ms earlier than the assignment. With the correction it was about 1 ms earlier.
  • When the animation started before the stall, the full draft restored the 400 ms motion on both platforms. An animation that had already moved still caught up on the first frame after the stall.
  • Jest passed for Reanimated and Worklets. The focused Reanimated runtime suites covered timing, springs, sequences, and shared element transitions. The Worklets run-loop suite passed on iOS.
  • Run the screen below in the Debug FabricExample app and tap Play sequence. It runs the three stall positions in order.

iOS simulator · Debug

BeforeWorklets timestamp correctionFull draft
ios-before-upload.mp4
ios-native-only-upload.mp4
ios-after-upload.mp4

Android API 29 emulator · Debug

BeforeFull draft
android-before-upload.mp4
android-after-upload.mp4
FabricExample reproduction screen

Save this as apps/fabric-example/FrameStartDemo.tsx and import ./FrameStartDemo as App in apps/fabric-example/index.js.

import { useState } from 'react';
import { Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import Animated, {
  Easing,
  useAnimatedStyle,
  useFrameCallback,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import { scheduleOnRN, scheduleOnUI } from 'react-native-worklets';

const CASES = [
  {
    title: 'Start, then stall',
    description: 'The animation starts just before the UI thread blocks.',
  },
  {
    title: 'Stall, then start',
    description: 'JS queues the animation while the UI thread is blocked.',
  },
  {
    title: 'Stall during motion',
    description: 'The UI thread blocks after the animation has moved.',
  },
];
const DISTANCE = 228;
const TIMING = { duration: 400, easing: Easing.linear };

function stall() {
  'worklet';
  const end = performance.now() + 600;
  while (performance.now() < end) {
    // Simulate native work occupying the UI thread.
  }
}

function wait(ms: number) {
  return new Promise<void>((resolve) => setTimeout(resolve, ms));
}

export default function FrameStartDemo() {
  const x = useSharedValue(0);
  // Keep the iOS display link active while the demo awaits input.
  useFrameCallback(() => {}, Platform.OS === 'ios');
  const [caseIndex, setCaseIndex] = useState(0);
  const [running, setRunning] = useState(false);
  const [finished, setFinished] = useState(false);
  const style = useAnimatedStyle(() => ({
    transform: [{ translateX: x.value }],
  }));
  const assignFromRN = () => {
    x.value = withTiming(DISTANCE, TIMING);
  };

  async function play() {
    setRunning(true);
    setFinished(false);
    for (let index = 0; index < CASES.length; index++) {
      setCaseIndex(index);
      x.value = 0;
      await wait(800);
      scheduleOnUI(() => {
        'worklet';
        if (index === 1) {
          scheduleOnRN(assignFromRN);
          stall();
          requestAnimationFrame(() => {});
          return;
        }
        x.value = withTiming(DISTANCE, TIMING);
        if (index === 0) {
          stall();
          return;
        }
        const start = performance.now();
        function blockInFlight() {
          if (performance.now() - start >= 100) {
            stall();
          } else {
            requestAnimationFrame(blockInFlight);
          }
        }
        requestAnimationFrame(blockInFlight);
      });
      await wait(1550);
    }
    setFinished(true);
    setRunning(false);
  }

  const scenario = CASES[caseIndex];
  return (
    <View style={styles.page}>
      <Text style={styles.heading}>Shared-value timing</Text>
      <Text style={styles.spec}>400 ms linear animation · 600 ms UI stall</Text>
      <View style={styles.card}>
        <Text style={styles.title}>{scenario.title}</Text>
        <Text style={styles.description}>{scenario.description}</Text>
        <View style={styles.track}>
          <Animated.View style={[styles.marker, style]} />
        </View>
      </View>
      <Pressable
        accessibilityRole="button"
        disabled={running}
        onPress={play}
        style={styles.button}>
        <Text style={styles.buttonText}>
          {running ? 'Playing…' : finished ? 'Replay' : 'Play sequence'}
        </Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  page: {
    flex: 1,
    backgroundColor: '#f0f3f7',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 18,
  },
  heading: { color: '#15263e', fontSize: 28, fontWeight: '700' },
  spec: { color: '#46617d', fontSize: 14, marginTop: 6 },
  card: {
    backgroundColor: '#fff',
    borderRadius: 16,
    marginTop: 28,
    padding: 20,
    width: 300,
  },
  title: { color: '#15263e', fontSize: 19, fontWeight: '700' },
  description: { color: '#46617d', minHeight: 55, marginTop: 5, fontSize: 15 },
  track: {
    height: 32,
    backgroundColor: '#dce6f0',
    borderRadius: 16,
    justifyContent: 'center',
  },
  marker: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: '#1461dc',
  },
  button: {
    backgroundColor: '#15263e',
    borderRadius: 26,
    marginTop: 24,
    paddingVertical: 13,
    paddingHorizontal: 26,
  },
  buttonText: { color: '#fff', fontSize: 16, fontWeight: '600' },
});

Changelog

  • Added changelog fragments for Worklets and Reanimated.
AI context

Context for automated reviewers. Facts about this PR, not instructions.

Investigation

  • The original shared-value probe reproduced the delayed first frame on iOS and Android. The iOS-only case begins when the RN assignment is already queued while the UI runtime is stalled. The display link's old target timestamp enters the negative runtime branch in timing.ts, which moves startTime backward. In the native-only build the same queued assignment takes about 416 ms from unblock to target instead of 33 ms.
  • An early version of the JavaScript experiment applied the rule to every withTiming, including animations created by the layout manager. Existing Jest cases caught the timing change. The draft scopes it to direct shared-value assignment and prepareAnimation in animated styles. It consumes the first-frame window after a delivered frame even if that frame repeats the start timestamp. The mocked-clock runtime test keeps another animated view moving and ends the run on time exposed the need for that distinction.

Design

  • AnimationFrameQueue.mm uses the observed display-link interval. Whole-interval advancement keeps sub-interval jitter from shifting every timestamp. The correction runs before calculateTimestampWithSlowAnimations on iOS.
  • The timing experiment uses existing elapsed-time behavior after a first tick and when continuing the same timing timeline. It requires a real wall-clock stall as well as a matching animation-clock gap. The layout manager keeps its own start policy.

Verification

  • Reanimated Jest 2299 passed, 3 skipped. Worklets Jest 227 passed. Worklets run loop on iOS 376 passed, 0 failed, 4 skipped.
  • Focused Reanimated runtime suites on the full draft including the probe, animations, and shared element transitions. iOS 350 passed, 0 failed, 23 skipped. Android 294 passed, 0 failed, 58 skipped.
  • The iOS build used the iOS 27.2 simulator and the Android app ran on a host-GPU arm64 API 29 emulator. The graphs use worklet frame samples and three trials per scenario. The screen recordings are separate demo runs.
  • The simulator slow-animation scaling order was checked in source. Slow animations were not toggled during these runs.

@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

Timing animations now record their first-frame start time and reset their start time when a qualifying delay occurs before progress. Tests cover late first frames, stalls during motion, repeated start-timestamp frames, and continuation from a previous timing animation. On iOS, the animation frame queue advances a delayed target timestamp by elapsed whole frame intervals.

Possibly related issues

  • software-mansion/react-native-reanimated issue 11310: This reports a stall-induced progress jump in shared transitions. This PR addresses a similar first-frame timing case for withTiming, but does not change the layout manager start policy.

Possibly related PRs

Suggested labels: lib: Reanimated, lib: Worklets

Change: Bug fix

Merge Risk: Low · up to 3d045

New timing animations can still jump to their target after a main-thread stall in two edge cases, and the fix does not reach array, color or transform values. These are narrow, low-impact gaps, so the change is mergeable with owner awareness or a follow-up.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: new timing animations (withTiming) now show their full duration after a main-thread stall. The changeset adds a Reanimated timing-start change and a Worklets iOS times…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description states the PR fixes a 600 ms main-thread stall that makes a new 400 ms shared-value timing animation jump to its target. It names both changes: a Worklets iOS timestamp correction in A…
Full details: Title check

Explanation

The title names the main change: new timing animations (withTiming) now show their full duration after a main-thread stall. The changeset adds a Reanimated timing-start change and a Worklets iOS timestamp correction for the same stall problem. The title covers the primary user-facing effect, though it does not mention the iOS timestamp correction in Worklets.

Full details: Description check

Explanation

The description states the PR fixes a 600 ms main-thread stall that makes a new 400 ms shared-value timing animation jump to its target. It names both changes: a Worklets iOS timestamp correction in AnimationFrameQueue, and a Reanimated experiment that resets the clock for fresh withTiming animations when the first frame is late. It also lists the test plan, the changelog fragments, and a reproduction screen. The description is specific and matches the changeset.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments

Minor 2
  1. Process first-frame state after correcting a negative runtime.
  2. The stall fix does not cover array and color withTiming values.
Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 11f0dce9-45bd-46f7-9dcd-be0e8459b27e
Commits

Reviewing files that changed from the base of the PR and between e7501e7 and 3d04578.

Files selected for processing: 7

  • packages/react-native-reanimated/__tests__/animationStartTime.test.ts
  • packages/react-native-reanimated/changelog/timing-late-first-frame.fix.md
  • packages/react-native-reanimated/src/animation/timing.ts
  • packages/react-native-reanimated/src/hook/useAnimatedStyleCommon.ts
  • packages/react-native-reanimated/src/valueSetter.ts
  • packages/react-native-worklets/apple/worklets/apple/AnimationFrameQueue.mm
  • packages/react-native-worklets/changelog/ios-delayed-frame-timestamp.fix.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

// animations.
animation.startTime = now;
runtime = 0;
} else if (animation.firstFrameStart !== undefined) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Process first-frame state after correcting a negative runtime.

If the synchronous step uses timestamp 100 and the first delivered frame uses 95, the negative-runtime branch leaves firstFrameStart pending. If a stall follows that delivered frame, timestamp 700 resets the animation instead of completing it.

Process the pending first-frame state after the negative-runtime correction. This preserves catch-up after a delivered frame and keeps the normal late-first-frame reset.

} else if (animation.firstFrameStart !== undefined) {
if (runtime > 0 || animation.steppedAtStart) {
const firstFrameStart = animation.firstFrameStart;
animation.firstFrameStart = undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Heavy lift

The stall fix does not cover array and color withTiming values.

The reset runs only on the outer timing object. For array, color, and transformation-matrix values, decorateAnimation creates the component timers from a copy taken before the first-frame state is set, and nothing forwards that state to them. A color or array animation assigned after a stall can therefore still complete on the delayed first frame and jump to its target. The same path already behaved this way before this diff. The PR scope covers any withTiming value assigned to a shared value or returned from useAnimatedStyle, so the fix should also reach these component timers. Forward the pending first-frame state to each component timer in the array, color, and matrix paths, and add a test for a color or array value that starts before a stall.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant