Skip to content

Polyfill requestIdleCallback when native is not available #8833

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/fiber/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ <h1>Fiber Example</h1>
return r;
}
var newSize = s / 2;
var slowDown = false;
var slowDown = true;
if (slowDown) {
var e = performance.now() + 0.8;
while (performance.now() < e) {
Expand Down
5 changes: 3 additions & 2 deletions src/renderers/art/ReactARTFiber.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const invariant = require('fbjs/lib/invariant');
const emptyObject = require('emptyObject');
const React = require('React');
const ReactFiberReconciler = require('ReactFiberReconciler');
const ReactDOMFrameScheduling = require('ReactDOMFrameScheduling');

const { Component } = React;

Expand Down Expand Up @@ -507,9 +508,9 @@ const ARTRenderer = ReactFiberReconciler({
return emptyObject;
},

scheduleAnimationCallback: window.requestAnimationFrame,
scheduleAnimationCallback: ReactDOMFrameScheduling.rAF,

scheduleDeferredCallback: window.requestIdleCallback,
scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,

shouldSetTextContent(props) {
return (
Expand Down
5 changes: 3 additions & 2 deletions src/renderers/dom/fiber/ReactDOMFiber.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ var ReactControlledComponent = require('ReactControlledComponent');
var ReactDOMComponentTree = require('ReactDOMComponentTree');
var ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
var ReactDOMFiberComponent = require('ReactDOMFiberComponent');
var ReactDOMFrameScheduling = require('ReactDOMFrameScheduling');
var ReactDOMInjection = require('ReactDOMInjection');
var ReactGenericBatching = require('ReactGenericBatching');
var ReactFiberReconciler = require('ReactFiberReconciler');
Expand Down Expand Up @@ -296,9 +297,9 @@ var DOMRenderer = ReactFiberReconciler({
parentInstance.removeChild(child);
},

scheduleAnimationCallback: window.requestAnimationFrame,
scheduleAnimationCallback: ReactDOMFrameScheduling.rAF,

scheduleDeferredCallback: window.requestIdleCallback,
scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,

useSyncScheduling: true,

Expand Down
149 changes: 149 additions & 0 deletions src/renderers/dom/fiber/ReactDOMFrameScheduling.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMFrameScheduling
* @flow
*/

'use strict';

// This a built-in polyfill for requestIdleCallback. It works by scheduling
// a requestAnimationFrame, store the time for the start of the frame, then
// schedule a postMessage which gets scheduled after paint. Within the
// postMessage handler do as much work as possible until 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.

import type { Deadline } from 'ReactFiberReconciler';

var invariant = require('invariant');

// TODO: There's no way to cancel these, because Fiber doesn't atm.
let rAF : (callback : (time : number) => void) => number;
let rIC : (callback : (deadline : Deadline) => void) => number;
if (typeof requestAnimationFrame !== 'function') {
invariant(
false,
'React depends on requestAnimationFrame. Make sure that you load a ' +
'polyfill in older browsers.'
);
} else if (typeof requestIdleCallback !== 'function') {
// Wrap requestAnimationFrame and polyfill requestIdleCallback.

var scheduledRAFCallback = null;
var scheduledRICCallback = null;

var isIdleScheduled = false;
var isAnimationFrameScheduled = false;

var frameDeadline = 0;
// We start out assuming that we run at 30fps but then the heuristic tracking
// will adjust this value to a faster fps if we get more frequent animation
// frames.
var previousFrameTime = 33;
var activeFrameTime = 33;

var frameDeadlineObject = {
timeRemaining: (
typeof performance === 'object' &&
typeof performance.now === 'function' ? function() {
// We assume that if we have a performance timer that the rAF callback
// gets a performance timer value. Not sure if this is always true.
return frameDeadline - performance.now();
} : function() {
// As a fallback we use Date.now.
return frameDeadline - Date.now();
Copy link
Contributor

Choose a reason for hiding this comment

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

Thinking out loud: performance.now() and Date.now() return very different values but they're being used interchangeably, driven by the param passed to requestAnimationFrame. Wouldn't this cause problems if we ever end up mixing the 2 due to polyfills? (requestAnimationFrame is supposed to be passed a time from performance.now() but some polyfills are Date based.)

Fortunately I don't think this is likely to occur. It seems both are supported by everything we target except for:

  • IE9, which supports neither; presumably this means we'd use Date.now for both.
  • iOS 8.4 which supports requestAnimationFrame but not performance.now. This version is 2.5 years old though and iOS has pretty strong upgrade adoption, so maybe we can just ignore this one point release.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

If iOS 8.4 supports requestAnimationFrame but not performance.now my hypothesis is that the value passed to requestAnimationFrame is the old Date.now version of requestAnimationFrame.

Yes, it is very possible that there is a browser that implements the new requestAnimationFrame without implementing performance.now. Seems unlikely though.

However, even more likely is that there are browsers out there that implement the old requestAnimationFrame while already implementing performance.now. That's very possible.

We could probably do a guess based on the value passed to requestAnimationFrame which one it is (if it is a very low number) and then switch dynamically between the two. For the case where the new rAF is implemented but no performance.now we could use a Date.now time stamp instead. I'd rather not complicate it unless we know of at least one browser where either of this happens though. Perhaps we can call on the community to help out identifying issues here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Hm. Actually I wonder if performance.now might be implemented behind performance.webkitNow in some cases which would trigger the bad case.

}
),
};

// We use the postMessage trick to defer idle work until after the repaint.
var messageKey =
'__reactIdleCallback$' + Math.random().toString(36).slice(2);
var idleTick = function(event) {
if (event.source !== window || event.data !== messageKey) {
return;
}
isIdleScheduled = false;
var callback = scheduledRICCallback;
scheduledRICCallback = null;
if (callback) {
callback(frameDeadlineObject);
}
};
// Assumes that we have addEventListener in this environment. Might need
// something better for old IE.
Copy link
Contributor

Choose a reason for hiding this comment

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

IE9+ supports addEventListener; as we no longer support IE8 this should be fine. 👍

window.addEventListener('message', idleTick, false);

var animationTick = function(rafTime) {
isAnimationFrameScheduled = false;
var nextFrameTime = rafTime - frameDeadline + activeFrameTime;
if (nextFrameTime < activeFrameTime && previousFrameTime < activeFrameTime) {
if (nextFrameTime < 8) {
// Defensive coding. We don't support higher frame rates than 120hz.
// If we get lower than that, it is probably a bug.
nextFrameTime = 8;
}
// If one frame goes long, then the next one can be short to catch up.
// If two frames are short in a row, then that's an indication that we
// actually have a higher frame rate than what we're currently optimizing.
// We adjust our heuristic dynamically accordingly. For example, if we're
// running on 120hz display or 90hz VR display.
// Take the max of the two in case one of them was an anomaly due to
// missed frame deadlines.
activeFrameTime = nextFrameTime < previousFrameTime ?
previousFrameTime : nextFrameTime;
} else {
previousFrameTime = nextFrameTime;
}
frameDeadline = rafTime + activeFrameTime;
if (!isIdleScheduled) {
isIdleScheduled = true;
window.postMessage(messageKey, '*');
}
var callback = scheduledRAFCallback;
scheduledRAFCallback = null;
if (callback) {
callback(rafTime);
}
};

rAF = function(callback : (time : number) => void) : number {
// This assumes that we only schedule one callback at a time because that's
// how Fiber uses it.
scheduledRAFCallback = callback;
if (!isAnimationFrameScheduled) {
// If rIC didn't already schedule one, we need to schedule a frame.
isAnimationFrameScheduled = true;
requestAnimationFrame(animationTick);
}
return 0;
};

rIC = function(callback : (deadline : Deadline) => void) : number {
// This assumes that we only schedule one callback at a time because that's
// how Fiber uses it.
scheduledRICCallback = callback;
if (!isAnimationFrameScheduled) {
// If rAF didn't already schedule one, we need to schedule a frame.
// TODO: If this rAF doesn't materialize because the browser throttles, we
// might want to still have setTimeout trigger rIC as a backup to ensure
// that we keep performing work.
isAnimationFrameScheduled = true;
requestAnimationFrame(animationTick);
}
return 0;
};
} else {
rAF = requestAnimationFrame;
rIC = requestIdleCallback;
}

exports.rAF = rAF;
exports.rIC = rIC;
4 changes: 2 additions & 2 deletions src/renderers/shared/fiber/ReactFiberReconciler.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ export type HostConfig<T, P, I, TI, PI, C, CX> = {
insertBefore(parentInstance : I | C, child : I | TI, beforeChild : I | TI) : void,
removeChild(parentInstance : I | C, child : I | TI) : void,

scheduleAnimationCallback(callback : () => void) : void,
scheduleDeferredCallback(callback : (deadline : Deadline) => void) : void,
scheduleAnimationCallback(callback : () => void) : number | void,
scheduleDeferredCallback(callback : (deadline : Deadline) => void) : number | void,

prepareForCommit() : void,
resetAfterCommit() : void,
Expand Down