-
Notifications
You must be signed in to change notification settings - Fork 47.9k
/
Copy pathReactNativeFrameScheduling.js
56 lines (45 loc) · 1.7 KB
/
ReactNativeFrameScheduling.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Deadline} from 'react-reconciler';
const hasNativePerformanceNow =
typeof performance === 'object' && typeof performance.now === 'function';
const now = hasNativePerformanceNow
? () => performance.now()
: () => Date.now();
type Callback = (deadline: Deadline) => void;
let scheduledCallback: Callback | null = null;
let frameDeadline: number = 0;
const frameDeadlineObject: Deadline = {
timeRemaining: () => frameDeadline - now(),
};
function setTimeoutCallback() {
// TODO (bvaughn) Hard-coded 5ms unblocks initial async testing.
// React API probably changing to boolean rather than time remaining.
// Longer-term plan is to rewrite this using shared memory,
// And just return the value of the bit as the boolean.
frameDeadline = now() + 5;
const callback = scheduledCallback;
scheduledCallback = null;
if (callback !== null) {
callback(frameDeadlineObject);
}
}
// RN has a poor polyfill for requestIdleCallback so we aren't using it.
// This implementation is only intended for short-term use anyway.
// We also don't implement cancel functionality b'c Fiber doesn't currently need it.
function scheduleDeferredCallback(callback: Callback): number {
// We assume only one callback is scheduled at a time b'c that's how Fiber works.
scheduledCallback = callback;
return setTimeout(setTimeoutCallback, 1);
}
function cancelDeferredCallback(callbackID: number) {
scheduledCallback = null;
clearTimeout(callbackID);
}
export {now, scheduleDeferredCallback, cancelDeferredCallback};