Skip to content

Commit 95ff2aa

Browse files
committed
Polyfill requestIdleCallback when native is not available
I introduce the ReactDOMFrameScheduling module which just exposes rIC and rAF. The polyfill works by scheduling a requestAnimationFrame, store the time for the start of the frame, then schedule a postMessage which gets scheduled after paint. The deadline is set to time + frame rate. By separating the idle call into a separate event tick we ensure that layout, paint and other browser work is counted against the available time. The frame rate is dynamically adjusted by tracking the minimum time between two rAF callbacks. This is not perfect because browsers can schedule multiple callbacks to catch up after a long frame. To compensate for this we only adjust if two consecutive periods are faster than normal. This seems to guarantee that we will hit frame deadlines and we don't end up dropping frames. However, there is still some lost time so we risk starving by not having enough idle time. Especially Firefox seems to have issues keeping up on the triangle demo However, that is also true for native rIC in Firefox. It seems like more render work is scheduled on the main thread pipeline and also that JS execution just generally has more overhead.
1 parent 06399b8 commit 95ff2aa

File tree

4 files changed

+156
-5
lines changed

4 files changed

+156
-5
lines changed

examples/fiber/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ <h1>Fiber Example</h1>
9090
return r;
9191
}
9292
var newSize = s / 2;
93-
var slowDown = false;
93+
var slowDown = true;
9494
if (slowDown) {
9595
var e = performance.now() + 0.8;
9696
while (performance.now() < e) {

src/renderers/art/ReactARTFiber.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ const invariant = require('fbjs/lib/invariant');
2121
const emptyObject = require('emptyObject');
2222
const React = require('React');
2323
const ReactFiberReconciler = require('ReactFiberReconciler');
24+
const ReactDOMFrameScheduling = require('ReactDOMFrameScheduling');
2425

2526
const { Component } = React;
2627

@@ -507,9 +508,9 @@ const ARTRenderer = ReactFiberReconciler({
507508
return emptyObject;
508509
},
509510

510-
scheduleAnimationCallback: window.requestAnimationFrame,
511+
scheduleAnimationCallback: ReactDOMFrameScheduling.rAF,
511512

512-
scheduleDeferredCallback: window.requestIdleCallback,
513+
scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,
513514

514515
shouldSetTextContent(props) {
515516
return (

src/renderers/dom/fiber/ReactDOMFiber.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ var ReactControlledComponent = require('ReactControlledComponent');
2020
var ReactDOMComponentTree = require('ReactDOMComponentTree');
2121
var ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
2222
var ReactDOMFiberComponent = require('ReactDOMFiberComponent');
23+
var ReactDOMFrameScheduling = require('ReactDOMFrameScheduling');
2324
var ReactDOMInjection = require('ReactDOMInjection');
2425
var ReactGenericBatching = require('ReactGenericBatching');
2526
var ReactFiberReconciler = require('ReactFiberReconciler');
@@ -296,9 +297,9 @@ var DOMRenderer = ReactFiberReconciler({
296297
parentInstance.removeChild(child);
297298
},
298299

299-
scheduleAnimationCallback: window.requestAnimationFrame,
300+
scheduleAnimationCallback: ReactDOMFrameScheduling.rAF,
300301

301-
scheduleDeferredCallback: window.requestIdleCallback,
302+
scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,
302303

303304
useSyncScheduling: true,
304305

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
/**
2+
* Copyright 2013-present, Facebook, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the BSD-style license found in the
6+
* LICENSE file in the root directory of this source tree. An additional grant
7+
* of patent rights can be found in the PATENTS file in the same directory.
8+
*
9+
* @providesModule ReactDOMFrameScheduling
10+
* @flow
11+
*/
12+
13+
'use strict';
14+
15+
// This a built-in polyfill for requestIdleCallback. It works by scheduling
16+
// a requestAnimationFrame, store the time for the start of the frame, then
17+
// schedule a postMessage which gets scheduled after paint. Within the
18+
// postMessage handler do as much work as possible until time + frame rate.
19+
// By separating the idle call into a separate event tick we ensure that
20+
// layout, paint and other browser work is counted against the available time.
21+
// The frame rate is dynamically adjusted.
22+
23+
var invariant = require('invariant');
24+
25+
// TODO: There's no way to cancel these, because Fiber doesn't atm.
26+
let rAF;
27+
let rIC;
28+
if (typeof requestAnimationFrame !== 'function') {
29+
invariant(
30+
false,
31+
'React depends on requestAnimationFrame. Make sure that you load a ' +
32+
'polyfill in older browsers.'
33+
);
34+
} else if (typeof requestIdleCallback !== 'function') {
35+
// Wrap requestAnimationFrame and polyfill requestIdleCallback.
36+
(function(requestAnimationFrame, global) {
37+
38+
var scheduledRAFCallback = null;
39+
var scheduledRICCallback = null;
40+
41+
var isIdleScheduled = false;
42+
var isAnimationFrameScheduled = false;
43+
44+
var frameDeadline = 0;
45+
// We start out assuming that we run at 30fps but then the heuristic tracking
46+
// will adjust this value to a faster fps if we get more frequent animation
47+
// frames.
48+
var previousFrameTime = 33;
49+
var activeFrameTime = 33;
50+
51+
var frameDeadlineObject = {
52+
timeRemaining: (
53+
typeof performance === 'object' &&
54+
typeof performance.now === 'function' ? function() {
55+
// We assume that if we have a performance timer that the rAF callback
56+
// gets a performance timer value. Not sure if this is always true.
57+
return frameDeadline - performance.now();
58+
} : function() {
59+
// As a fallback we use Date.now.
60+
return frameDeadline - Date.now();
61+
}
62+
),
63+
};
64+
65+
// We use the postMessage trick to defer idle work until after the repaint.
66+
var messageKey =
67+
'__reactIdleCallback$' + Math.random().toString(36).slice(2);
68+
function idleTick(event) {
69+
if (event.source !== global || event.data !== messageKey) {
70+
return;
71+
}
72+
isIdleScheduled = false;
73+
var callback = scheduledRICCallback;
74+
scheduledRICCallback = null;
75+
if (callback) {
76+
callback(frameDeadlineObject);
77+
}
78+
}
79+
// Assumes that we have addEventListener in this environment. Might need
80+
// something better for old IE.
81+
global.addEventListener('message', idleTick, false);
82+
83+
function animationTick(rafTime) {
84+
isAnimationFrameScheduled = false;
85+
var nextFrameTime = rafTime - frameDeadline + activeFrameTime;
86+
if (nextFrameTime < activeFrameTime && previousFrameTime < activeFrameTime) {
87+
if (nextFrameTime < 8) {
88+
// Defensive coding. We don't support higher frame rates than 120hz.
89+
// If we get lower than that, it is probably a bug.
90+
nextFrameTime = 8;
91+
}
92+
// If one frame goes long, then the next one can be short to catch up.
93+
// If two frames are short in a row, then that's an indication that we
94+
// actually have a higher frame rate than what we're currently optimizing.
95+
// We adjust our heuristic dynamically accordingly. For example, if we're
96+
// running on 120hz display or 90hz VR display.
97+
// Take the max of the two in case one of them was an anomaly due to
98+
// missed frame deadlines.
99+
activeFrameTime = nextFrameTime < previousFrameTime ?
100+
previousFrameTime : nextFrameTime;
101+
} else {
102+
previousFrameTime = nextFrameTime;
103+
}
104+
frameDeadline = rafTime + activeFrameTime;
105+
if (!isIdleScheduled) {
106+
isIdleScheduled = true;
107+
global.postMessage(messageKey, '*');
108+
}
109+
var callback = scheduledRAFCallback;
110+
scheduledRAFCallback = null;
111+
if (callback) {
112+
callback(rafTime);
113+
}
114+
}
115+
116+
rIC = function(callback) {
117+
// This assumes that we only schedule one callback at a time because that's
118+
// how Fiber uses it.
119+
scheduledRICCallback = callback;
120+
if (!isAnimationFrameScheduled) {
121+
// If rAF didn't already schedule one, we need to schedule a frame.
122+
// TODO: If this rAF doesn't materialize because the browser throttles, we
123+
// might want to still have setTimeout trigger rIC as a backup to ensure
124+
// that we keep performing work.
125+
isAnimationFrameScheduled = true;
126+
requestAnimationFrame(animationTick);
127+
}
128+
};
129+
130+
rAF = function(callback) {
131+
// This assumes that we only schedule one callback at a time because that's
132+
// how Fiber uses it.
133+
scheduledRAFCallback = callback;
134+
if (!isAnimationFrameScheduled) {
135+
// If rIC didn't already schedule one, we need to schedule a frame.
136+
isAnimationFrameScheduled = true;
137+
requestAnimationFrame(animationTick);
138+
}
139+
};
140+
141+
})(requestAnimationFrame, window);
142+
} else {
143+
// We use native requestIdleCallback if available.
144+
rIC = requestIdleCallback;
145+
rAF = requestAnimationFrame;
146+
}
147+
148+
exports.rIC = rIC;
149+
exports.rAF = rAF;

0 commit comments

Comments
 (0)