@samitouri / QOS-React-2 / commits / 75ab53b9e1

[scheduler] Yield many times per frame, no rAF (#16214)

Adds experimental flag to yield many times per frame using a message event loop, instead of the current approach of guessing the next vsync and yielding at the end of the frame. This new approach forgoes a `requestAnimationFrame` entirely. It posts a message event and performs a small amount of work (5ms) before yielding to the browser, regardless of where it might be in the vsync cycle. At the end of the event, if there's work left over, it posts another message event. This should keep the main thread responsive even for really high frame rates. It also shouldn't matter if the hardware frame rate changes after page load (our current heuristic only detects if the frame rate increases, not decreases). The main risk is that yielding more often will exacerbate main thread contention with other browser tasks. Let's try it and see.

Andrew Clark committed Jul 26, 2019 at 15:43 UTC 75ab53b9e1de662121e68dabb010655943d28d11
5 files changed +538 -414
packages/scheduler/src/SchedulerFeatureFlags.js
+1
@@ -10,3 +10,4 @@ export const enableSchedulerDebugging = false;
10 export const enableIsInputPending = false;
11 export const requestIdleCallbackBeforeFirstFrame = false;
12 export const requestTimerEventBeforeFirstFrame = false;
13 +export const enableMessageLoopImplementation = false;
packages/scheduler/src/__tests__/SchedulerBrowser-test.internal.js new
+422
@@ -0,0 +1,422 @@
1 +/**
2 + * Copyright (c) Facebook, Inc. and its affiliates.
3 + *
4 + * This source code is licensed under the MIT license found in the
5 + * LICENSE file in the root directory of this source tree.
6 + *
7 + * @emails react-core
8 + * @jest-environment node
9 + */
10 +
11 +/* eslint-disable no-for-of-loops/no-for-of-loops */
12 +
13 +'use strict';
14 +
15 +let Scheduler;
16 +let runtime;
17 +let performance;
18 +let scheduleCallback;
19 +let NormalPriority;
20 +
21 +// The Scheduler implementation uses browser APIs like `MessageChannel`,
22 +// `requestAnimationFrame`, and `setTimeout` to schedule work on the main
23 +// thread. Most of our tests treat these as implementation details; however, the
24 +// sequence and timing of these APIs are not precisely specified, and can vary
25 +// wildly across browsers.
26 +//
27 +// To prevent regressions, we need the ability to simulate specific edge cases
28 +// that we may encounter in various browsers.
29 +//
30 +// This test suite mocks all browser methods used in our implementation. It
31 +// assumes as little as possible about the order and timing of events. The only
32 +// thing it assumes is that requestAnimationFrame is passed a frame time that is
33 +// equal to or less than the time returned by performance.now. Everything else
34 +// can be controlled at will.
35 +//
36 +// It also includes Scheduler-specific invariants, e.g. only one rAF callback
37 +// can be scheduled at a time.
38 +describe('SchedulerBrowser', () => {
39 + function beforeAndAfterHooks(enableMessageLoopImplementation) {
40 + beforeEach(() => {
41 + jest.resetModules();
42 +
43 + // Un-mock scheduler
44 + jest.mock('scheduler', () => require.requireActual('scheduler'));
45 + jest.mock('scheduler/src/SchedulerHostConfig', () =>
46 + require.requireActual(
47 + 'scheduler/src/forks/SchedulerHostConfig.default.js',
48 + ),
49 + );
50 +
51 + runtime = installMockBrowserRuntime();
52 + performance = window.performance;
53 + require('scheduler/src/SchedulerFeatureFlags').enableMessageLoopImplementation = enableMessageLoopImplementation;
54 + Scheduler = require('scheduler');
55 + scheduleCallback = Scheduler.unstable_scheduleCallback;
56 + NormalPriority = Scheduler.unstable_NormalPriority;
57 + });
58 +
59 + afterEach(() => {
60 + if (!runtime.isLogEmpty()) {
61 + throw Error('Test exited without clearing log.');
62 + }
63 + });
64 + }
65 +
66 + function installMockBrowserRuntime() {
67 + let VSYNC_INTERVAL = 33.33;
68 +
69 + let hasPendingMessageEvent = false;
70 +
71 + let rAFCallbackIDCounter = 0;
72 + let rAFCallback = null;
73 + let isRunningRAFCallback = false;
74 +
75 + let rICCallbackIDCounter = 0;
76 + let rICCallback = null;
77 +
78 + let timerIDCounter = 0;
79 + // let timerIDs = new Map();
80 +
81 + let eventLog = [];
82 +
83 + const window = {};
84 + global.window = window;
85 +
86 + let currentTime = 0;
87 +
88 + window.performance = {
89 + now() {
90 + return currentTime;
91 + },
92 + };
93 + window.requestAnimationFrame = cb => {
94 + if (rAFCallback !== null) {
95 + throw Error('rAF already scheduled');
96 + }
97 + if (isRunningRAFCallback) {
98 + log('Request Animation Frame [Reposted]');
99 + } else {
100 + log('Request Animation Frame');
101 + }
102 + rAFCallback = cb;
103 + return rAFCallbackIDCounter++;
104 + };
105 + window.cancelAnimationFrame = id => {
106 + rAFCallback = null;
107 + };
108 +
109 + window.requestIdleCallback = cb => {
110 + if (rICCallback !== null) {
111 + throw Error('rAF already scheduled');
112 + }
113 + log('Request Idle Callback');
114 + rICCallback = cb;
115 + return rICCallbackIDCounter++;
116 + };
117 + window.cancelIdleCallback = id => {
118 + rICCallback = null;
119 + };
120 +
121 + window.setTimeout = (cb, delay) => {
122 + const id = timerIDCounter++;
123 + log(`Set Timer`);
124 + // TODO
125 + return id;
126 + };
127 + window.clearTimeout = id => {
128 + // TODO
129 + };
130 +
131 + const port1 = {};
132 + const port2 = {
133 + postMessage() {
134 + if (hasPendingMessageEvent) {
135 + throw Error('Message event already scheduled');
136 + }
137 + log('Post Message');
138 + hasPendingMessageEvent = true;
139 + },
140 + };
141 + global.MessageChannel = function MessageChannel() {
142 + this.port1 = port1;
143 + this.port2 = port2;
144 + };
145 +
146 + function ensureLogIsEmpty() {
147 + if (eventLog.length !== 0) {
148 + throw Error('Log is not empty. Call assertLog before continuing.');
149 + }
150 + }
151 + function setHardwareFrameRate(fps) {
152 + VSYNC_INTERVAL = 1000 / fps;
153 + }
154 + function advanceTime(ms) {
155 + currentTime += ms;
156 + }
157 + function advanceTimeToNextFrame() {
158 + const targetTime =
159 + Math.ceil(currentTime / VSYNC_INTERVAL) * VSYNC_INTERVAL;
160 + if (targetTime === currentTime) {
161 + currentTime += VSYNC_INTERVAL;
162 + } else {
163 + currentTime = targetTime;
164 + }
165 + }
166 + function getMostRecentFrameNumber() {
167 + return Math.floor(currentTime / VSYNC_INTERVAL);
168 + }
169 + function fireMessageEvent() {
170 + ensureLogIsEmpty();
171 + if (!hasPendingMessageEvent) {
172 + throw Error('No message event was scheduled');
173 + }
174 + hasPendingMessageEvent = false;
175 + const onMessage = port1.onmessage;
176 + log('Message Event');
177 + onMessage();
178 + }
179 + function fireAnimationFrame() {
180 + ensureLogIsEmpty();
181 + if (isRunningRAFCallback) {
182 + throw Error('Cannot fire animation frame from inside another event.');
183 + }
184 + if (rAFCallback === null) {
185 + throw Error('No rAF scheduled.');
186 + }
187 + const mostRecentFrameNumber = getMostRecentFrameNumber();
188 + const rAFTime = mostRecentFrameNumber * VSYNC_INTERVAL;
189 + const cb = rAFCallback;
190 + rAFCallback = null;
191 + log(`Animation Frame [${mostRecentFrameNumber}]`);
192 + isRunningRAFCallback = true;
193 + try {
194 + cb(rAFTime);
195 + } finally {
196 + isRunningRAFCallback = false;
197 + }
198 + }
199 + function fireRIC() {
200 + ensureLogIsEmpty();
201 + if (rICCallback === null) {
202 + throw Error('No rIC scheduled.');
203 + }
204 + const cb = rICCallback;
205 + rICCallback = null;
206 + log('Idle Callback');
207 + cb();
208 + }
209 + function log(val) {
210 + eventLog.push(val);
211 + }
212 + function isLogEmpty() {
213 + return eventLog.length === 0;
214 + }
215 + function assertLog(expected) {
216 + const actual = eventLog;
217 + eventLog = [];
218 + expect(actual).toEqual(expected);
219 + }
220 + return {
221 + setHardwareFrameRate,
222 + advanceTime,
223 + advanceTimeToNextFrame,
224 + getMostRecentFrameNumber,
225 + fireMessageEvent,
226 + fireAnimationFrame,
227 + fireRIC,
228 + log,
229 + isLogEmpty,
230 + assertLog,
231 + };
232 + }
233 +
234 + describe('rAF aligned frame boundaries', () => {
235 + const enableMessageLoopImplementation = false;
236 + beforeAndAfterHooks(enableMessageLoopImplementation);
237 +
238 + it('callback with continuation', () => {
239 + scheduleCallback(NormalPriority, () => {
240 + runtime.log('Task');
241 + while (!Scheduler.unstable_shouldYield()) {
242 + runtime.advanceTime(1);
243 + }
244 + runtime.log(`Yield at ${performance.now()}ms`);
245 + return () => {
246 + runtime.log('Continuation');
247 + };
248 + });
249 + runtime.assertLog(['Request Animation Frame']);
250 +
251 + runtime.fireAnimationFrame();
252 + runtime.assertLog([
253 + 'Animation Frame [0]',
254 + 'Request Animation Frame [Reposted]',
255 + 'Set Timer',
256 + 'Post Message',
257 + ]);
258 + runtime.fireMessageEvent();
259 + runtime.assertLog(['Message Event', 'Task', 'Yield at 34ms']);
260 +
261 + runtime.fireAnimationFrame();
262 + runtime.assertLog([
263 + 'Animation Frame [1]',
264 + 'Request Animation Frame [Reposted]',
265 + 'Set Timer',
266 + 'Post Message',
267 + ]);
268 +
269 + runtime.fireMessageEvent();
270 + runtime.assertLog(['Message Event', 'Continuation']);
271 +
272 + runtime.advanceTimeToNextFrame();
273 + runtime.fireAnimationFrame();
274 + runtime.assertLog(['Animation Frame [2]']);
275 + });
276 +
277 + it('two rAF calls in the same frame', () => {
278 + scheduleCallback(NormalPriority, () => runtime.log('A'));
279 + runtime.assertLog(['Request Animation Frame']);
280 + runtime.fireAnimationFrame();
281 + runtime.assertLog([
282 + 'Animation Frame [0]',
283 + 'Request Animation Frame [Reposted]',
284 + 'Set Timer',
285 + 'Post Message',
286 + ]);
287 + runtime.fireMessageEvent();
288 + runtime.assertLog(['Message Event', 'A']);
289 +
290 + // The Scheduler queue is now empty. We're still in frame 0.
291 + expect(runtime.getMostRecentFrameNumber()).toBe(0);
292 +
293 + // Post a task to Scheduler.
294 + scheduleCallback(NormalPriority, () => runtime.log('B'));
295 +
296 + // Did not request another animation frame, since one was already scheduled
297 + // during the previous rAF.
298 + runtime.assertLog([]);
299 +
300 + // Fire the animation frame.
301 + runtime.fireAnimationFrame();
302 + runtime.assertLog([
303 + 'Animation Frame [0]',
304 + 'Request Animation Frame [Reposted]',
305 + 'Set Timer',
306 + 'Post Message',
307 + ]);
308 +
309 + runtime.fireMessageEvent();
310 + runtime.assertLog(['Message Event', 'B']);
311 + });
312 +
313 + it('adjusts frame rate by measuring inteval between rAF events', () => {
314 + runtime.setHardwareFrameRate(60);
315 +
316 + scheduleCallback(NormalPriority, () => runtime.log('Tick'));
317 + runtime.assertLog(['Request Animation Frame']);
318 +
319 + // Need to measure two consecutive intervals between frames.
320 + for (let i = 0; i < 2; i++) {
321 + runtime.fireAnimationFrame();
322 + runtime.assertLog([
323 + `Animation Frame [${runtime.getMostRecentFrameNumber()}]`,
324 + 'Request Animation Frame [Reposted]',
325 + 'Set Timer',
326 + 'Post Message',
327 + ]);
328 + runtime.fireMessageEvent();
329 + runtime.assertLog(['Message Event', 'Tick']);
330 + scheduleCallback(NormalPriority, () => runtime.log('Tick'));
331 + runtime.advanceTimeToNextFrame();
332 + }
333 +
334 + // Scheduler should observe that it's receiving rAFs every 16.6 ms and
335 + // adjust its frame rate accordingly. Test by blocking the thread until
336 + // Scheduler tells us to yield. Then measure how much time has elapsed.
337 + const start = performance.now();
338 + scheduleCallback(NormalPriority, () => {
339 + while (!Scheduler.unstable_shouldYield()) {
340 + runtime.advanceTime(1);
341 + }
342 + });
343 + runtime.fireAnimationFrame();
344 + runtime.assertLog([
345 + `Animation Frame [${runtime.getMostRecentFrameNumber()}]`,
346 + 'Request Animation Frame [Reposted]',
347 + 'Set Timer',
348 + 'Post Message',
349 + ]);
350 + runtime.fireMessageEvent();
351 + runtime.assertLog(['Message Event', 'Tick']);
352 + const end = performance.now();
353 +
354 + // Check how much time elapsed in the frame.
355 + expect(end - start).toEqual(17);
356 + });
357 + });
358 +
359 + describe('message event loop', () => {
360 + const enableMessageLoopImplementation = true;
361 + beforeAndAfterHooks(enableMessageLoopImplementation);
362 +
363 + it('task with continutation', () => {
364 + scheduleCallback(NormalPriority, () => {
365 + runtime.log('Task');
366 + while (!Scheduler.unstable_shouldYield()) {
367 + runtime.advanceTime(1);
368 + }
369 + runtime.log(`Yield at ${performance.now()}ms`);
370 + return () => {
371 + runtime.log('Continuation');
372 + };
373 + });
374 + runtime.assertLog(['Post Message']);
375 +
376 + runtime.fireMessageEvent();
377 + runtime.assertLog([
378 + 'Message Event',
379 + 'Task',
380 + 'Yield at 5ms',
381 + 'Post Message',
382 + ]);
383 +
384 + runtime.fireMessageEvent();
385 + runtime.assertLog(['Message Event', 'Continuation']);
386 + });
387 +
388 + it('task that throws', () => {
389 + scheduleCallback(NormalPriority, () => {
390 + runtime.log('Oops!');
391 + throw Error('Oops!');
392 + });
393 + scheduleCallback(NormalPriority, () => {
394 + runtime.log('Yay');
395 + });
396 + runtime.assertLog(['Post Message']);
397 +
398 + expect(() => runtime.fireMessageEvent()).toThrow('Oops!');
399 + runtime.assertLog(['Message Event', 'Oops!', 'Post Message']);
400 +
401 + runtime.fireMessageEvent();
402 + runtime.assertLog(['Message Event', 'Yay']);
403 + });
404 +
405 + it('schedule new task after queue has emptied', () => {
406 + scheduleCallback(NormalPriority, () => {
407 + runtime.log('A');
408 + });
409 +
410 + runtime.assertLog(['Post Message']);
411 + runtime.fireMessageEvent();
412 + runtime.assertLog(['Message Event', 'A']);
413 +
414 + scheduleCallback(NormalPriority, () => {
415 + runtime.log('B');
416 + });
417 + runtime.assertLog(['Post Message']);
418 + runtime.fireMessageEvent();
419 + runtime.assertLog(['Message Event', 'B']);
420 + });
421 + });
422 +});
packages/scheduler/src/__tests__/SchedulerBrowser-test.js deleted
-350
@@ -1,350 +0,0 @@
1 -/**
2 - * Copyright (c) Facebook, Inc. and its affiliates.
3 - *
4 - * This source code is licensed under the MIT license found in the
5 - * LICENSE file in the root directory of this source tree.
6 - *
7 - * @emails react-core
8 - * @jest-environment node
9 - */
10 -
11 -/* eslint-disable no-for-of-loops/no-for-of-loops */
12 -
13 -'use strict';
14 -
15 -let Scheduler;
16 -let runtime;
17 -let performance;
18 -let scheduleCallback;
19 -let NormalPriority;
20 -
21 -// The Scheduler implementation uses browser APIs like `MessageChannel`,
22 -// `requestAnimationFrame`, and `setTimeout` to schedule work on the main
23 -// thread. Most of our tests treat these as implementation details; however, the
24 -// sequence and timing of these APIs are not precisely specified, and can vary
25 -// wildly across browsers.
26 -//
27 -// To prevent regressions, we need the ability to simulate specific edge cases
28 -// that we may encounter in various browsers.
29 -//
30 -// This test suite mocks all browser methods used in our implementation. It
31 -// assumes as little as possible about the order and timing of events. The only
32 -// thing it assumes is that requestAnimationFrame is passed a frame time that is
33 -// equal to or less than the time returned by performance.now. Everything else
34 -// can be controlled at will.
35 -//
36 -// It also includes Scheduler-specific invariants, e.g. only one rAF callback
37 -// can be scheduled at a time.
38 -describe('SchedulerBrowser', () => {
39 - beforeEach(() => {
40 - jest.resetModules();
41 -
42 - // Un-mock scheduler
43 - jest.mock('scheduler', () => require.requireActual('scheduler'));
44 - jest.mock('scheduler/src/SchedulerHostConfig', () =>
45 - require.requireActual(
46 - 'scheduler/src/forks/SchedulerHostConfig.default.js',
47 - ),
48 - );
49 -
50 - runtime = installMockBrowserRuntime();
51 - performance = window.performance;
52 - Scheduler = require('scheduler');
53 - scheduleCallback = Scheduler.unstable_scheduleCallback;
54 - NormalPriority = Scheduler.unstable_NormalPriority;
55 - });
56 -
57 - afterEach(() => {
58 - if (!runtime.isLogEmpty()) {
59 - throw Error('Test exited without clearing log.');
60 - }
61 - });
62 -
63 - function installMockBrowserRuntime() {
64 - let VSYNC_INTERVAL = 33.33;
65 -
66 - let hasPendingMessageEvent = false;
67 -
68 - let rAFCallbackIDCounter = 0;
69 - let rAFCallback = null;
70 - let isRunningRAFCallback = false;
71 -
72 - let rICCallbackIDCounter = 0;
73 - let rICCallback = null;
74 -
75 - let timerIDCounter = 0;
76 - // let timerIDs = new Map();
77 -
78 - let eventLog = [];
79 -
80 - const window = {};
81 - global.window = window;
82 -
83 - let currentTime = 0;
84 -
85 - window.performance = {
86 - now() {
87 - return currentTime;
88 - },
89 - };
90 - window.requestAnimationFrame = cb => {
91 - if (rAFCallback !== null) {
92 - throw Error('rAF already scheduled');
93 - }
94 - if (isRunningRAFCallback) {
95 - log('Request Animation Frame [Reposted]');
96 - } else {
97 - log('Request Animation Frame');
98 - }
99 - rAFCallback = cb;
100 - return rAFCallbackIDCounter++;
101 - };
102 - window.cancelAnimationFrame = id => {
103 - rAFCallback = null;
104 - };
105 -
106 - window.requestIdleCallback = cb => {
107 - if (rICCallback !== null) {
108 - throw Error('rAF already scheduled');
109 - }
110 - log('Request Idle Callback');
111 - rICCallback = cb;
112 - return rICCallbackIDCounter++;
113 - };
114 - window.cancelIdleCallback = id => {
115 - rICCallback = null;
116 - };
117 -
118 - window.setTimeout = (cb, delay) => {
119 - const id = timerIDCounter++;
120 - log(`Set Timer`);
121 - // TODO
122 - return id;
123 - };
124 - window.clearTimeout = id => {
125 - // TODO
126 - };
127 -
128 - const port1 = {};
129 - const port2 = {
130 - postMessage() {
131 - if (hasPendingMessageEvent) {
132 - throw Error('Message event already scheduled');
133 - }
134 - log('Post Message');
135 - hasPendingMessageEvent = true;
136 - },
137 - };
138 - global.MessageChannel = function MessageChannel() {
139 - this.port1 = port1;
140 - this.port2 = port2;
141 - };
142 -
143 - function ensureLogIsEmpty() {
144 - if (eventLog.length !== 0) {
145 - throw Error('Log is not empty. Call assertLog before continuing.');
146 - }
147 - }
148 - function setHardwareFrameRate(fps) {
149 - VSYNC_INTERVAL = 1000 / fps;
150 - }
151 - function advanceTime(ms) {
152 - currentTime += ms;
153 - }
154 - function advanceTimeToNextFrame() {
155 - const targetTime =
156 - Math.ceil(currentTime / VSYNC_INTERVAL) * VSYNC_INTERVAL;
157 - if (targetTime === currentTime) {
158 - currentTime += VSYNC_INTERVAL;
159 - } else {
160 - currentTime = targetTime;
161 - }
162 - }
163 - function getMostRecentFrameNumber() {
164 - return Math.floor(currentTime / VSYNC_INTERVAL);
165 - }
166 - function fireMessageEvent() {
167 - ensureLogIsEmpty();
168 - if (!hasPendingMessageEvent) {
169 - throw Error('No message event was scheduled');
170 - }
171 - hasPendingMessageEvent = false;
172 - const onMessage = port1.onmessage;
173 - log('Message Event');
174 - onMessage();
175 - }
176 - function fireAnimationFrame() {
177 - ensureLogIsEmpty();
178 - if (isRunningRAFCallback) {
179 - throw Error('Cannot fire animation frame from inside another event.');
180 - }
181 - if (rAFCallback === null) {
182 - throw Error('No rAF scheduled.');
183 - }
184 - const mostRecentFrameNumber = getMostRecentFrameNumber();
185 - const rAFTime = mostRecentFrameNumber * VSYNC_INTERVAL;
186 - const cb = rAFCallback;
187 - rAFCallback = null;
188 - log(`Animation Frame [${mostRecentFrameNumber}]`);
189 - isRunningRAFCallback = true;
190 - try {
191 - cb(rAFTime);
192 - } finally {
193 - isRunningRAFCallback = false;
194 - }
195 - }
196 - function fireRIC() {
197 - ensureLogIsEmpty();
198 - if (rICCallback === null) {
199 - throw Error('No rIC scheduled.');
200 - }
201 - const cb = rICCallback;
202 - rICCallback = null;
203 - log('Idle Callback');
204 - cb();
205 - }
206 - function log(val) {
207 - eventLog.push(val);
208 - }
209 - function isLogEmpty() {
210 - return eventLog.length === 0;
211 - }
212 - function assertLog(expected) {
213 - const actual = eventLog;
214 - eventLog = [];
215 - expect(actual).toEqual(expected);
216 - }
217 - return {
218 - setHardwareFrameRate,
219 - advanceTime,
220 - advanceTimeToNextFrame,
221 - getMostRecentFrameNumber,
222 - fireMessageEvent,
223 - fireAnimationFrame,
224 - fireRIC,
225 - log,
226 - isLogEmpty,
227 - assertLog,
228 - };
229 - }
230 -
231 - it('callback with continuation', () => {
232 - scheduleCallback(NormalPriority, () => {
233 - runtime.log('Task');
234 - while (!Scheduler.unstable_shouldYield()) {
235 - runtime.advanceTime(1);
236 - }
237 - runtime.log(`Yield at ${performance.now()}ms`);
238 - return () => {
239 - runtime.log('Continuation');
240 - };
241 - });
242 - runtime.assertLog(['Request Animation Frame']);
243 -
244 - runtime.fireAnimationFrame();
245 - runtime.assertLog([
246 - 'Animation Frame [0]',
247 - 'Request Animation Frame [Reposted]',
248 - 'Set Timer',
249 - 'Post Message',
250 - ]);
251 - runtime.fireMessageEvent();
252 - runtime.assertLog(['Message Event', 'Task', 'Yield at 34ms']);
253 -
254 - runtime.fireAnimationFrame();
255 - runtime.assertLog([
256 - 'Animation Frame [1]',
257 - 'Request Animation Frame [Reposted]',
258 - 'Set Timer',
259 - 'Post Message',
260 - ]);
261 -
262 - runtime.fireMessageEvent();
263 - runtime.assertLog(['Message Event', 'Continuation']);
264 -
265 - runtime.advanceTimeToNextFrame();
266 - runtime.fireAnimationFrame();
267 - runtime.assertLog(['Animation Frame [2]']);
268 - });
269 -
270 - it('two rAF calls in the same frame', () => {
271 - scheduleCallback(NormalPriority, () => runtime.log('A'));
272 - runtime.assertLog(['Request Animation Frame']);
273 - runtime.fireAnimationFrame();
274 - runtime.assertLog([
275 - 'Animation Frame [0]',
276 - 'Request Animation Frame [Reposted]',
277 - 'Set Timer',
278 - 'Post Message',
279 - ]);
280 - runtime.fireMessageEvent();
281 - runtime.assertLog(['Message Event', 'A']);
282 -
283 - // The Scheduler queue is now empty. We're still in frame 0.
284 - expect(runtime.getMostRecentFrameNumber()).toBe(0);
285 -
286 - // Post a task to Scheduler.
287 - scheduleCallback(NormalPriority, () => runtime.log('B'));
288 -
289 - // Did not request another animation frame, since one was already scheduled
290 - // during the previous rAF.
291 - runtime.assertLog([]);
292 -
293 - // Fire the animation frame.
294 - runtime.fireAnimationFrame();
295 - runtime.assertLog([
296 - 'Animation Frame [0]',
297 - 'Request Animation Frame [Reposted]',
298 - 'Set Timer',
299 - 'Post Message',
300 - ]);
301 -
302 - runtime.fireMessageEvent();
303 - runtime.assertLog(['Message Event', 'B']);
304 - });
305 -
306 - it('adjusts frame rate by measuring inteval between rAF events', () => {
307 - runtime.setHardwareFrameRate(60);
308 -
309 - scheduleCallback(NormalPriority, () => runtime.log('Tick'));
310 - runtime.assertLog(['Request Animation Frame']);
311 -
312 - // Need to measure two consecutive intervals between frames.
313 - for (let i = 0; i < 2; i++) {
314 - runtime.fireAnimationFrame();
315 - runtime.assertLog([
316 - `Animation Frame [${runtime.getMostRecentFrameNumber()}]`,
317 - 'Request Animation Frame [Reposted]',
318 - 'Set Timer',
319 - 'Post Message',
320 - ]);
321 - runtime.fireMessageEvent();
322 - runtime.assertLog(['Message Event', 'Tick']);
323 - scheduleCallback(NormalPriority, () => runtime.log('Tick'));
324 - runtime.advanceTimeToNextFrame();
325 - }
326 -
327 - // Scheduler should observe that it's receiving rAFs every 16.6 ms and
328 - // adjust its frame rate accordingly. Test by blocking the thread until
329 - // Scheduler tells us to yield. Then measure how much time has elapsed.
330 - const start = performance.now();
331 - scheduleCallback(NormalPriority, () => {
332 - while (!Scheduler.unstable_shouldYield()) {
333 - runtime.advanceTime(1);
334 - }
335 - });
336 - runtime.fireAnimationFrame();
337 - runtime.assertLog([
338 - `Animation Frame [${runtime.getMostRecentFrameNumber()}]`,
339 - 'Request Animation Frame [Reposted]',
340 - 'Set Timer',
341 - 'Post Message',
342 - ]);
343 - runtime.fireMessageEvent();
344 - runtime.assertLog(['Message Event', 'Tick']);
345 - const end = performance.now();
346 -
347 - // Check how much time elapsed in the frame.
348 - expect(end - start).toEqual(17);
349 - });
350 -});
packages/scheduler/src/forks/SchedulerFeatureFlags.www.js
+1
@@ -11,4 +11,5 @@ export const {
11 enableSchedulerDebugging,
12 requestIdleCallbackBeforeFirstFrame,
13 requestTimerEventBeforeFirstFrame,
14 + enableMessageLoopImplementation,
15 } = require('SchedulerFeatureFlags');
packages/scheduler/src/forks/SchedulerHostConfig.default.js
+114 -64
@@ -9,6 +9,7 @@ import {
9 enableIsInputPending,
10 requestIdleCallbackBeforeFirstFrame as requestIdleCallbackBeforeFirstFrameFlag,
11 requestTimerEventBeforeFirstFrame,
12 + enableMessageLoopImplementation,
13 } from '../SchedulerFeatureFlags';
14
15 // The DOM Scheduler implementation is similar to requestIdleCallback. It
@@ -116,14 +117,22 @@ if (
117 : () => Date.now();
118
119 let isRAFLoopRunning = false;
120 + let isMessageLoopRunning = false;
121 let scheduledHostCallback = null;
122 let rAFTimeoutID = -1;
123 let taskTimeoutID = -1;
124
123 - // We start out assuming that we run at 30fps but then the heuristic tracking
124 - // will adjust this value to a faster fps if we get more frequent animation
125 - // frames.
126 - let frameLength = 33.33;
125 + let frameLength = enableMessageLoopImplementation
126 + ? // We won't attempt to align with the vsync. Instead we'll yield multiple
127 + // times per frame, often enough to keep it responsive even at really
128 + // high frame rates > 120.
129 + 5
130 + : // Use a heuristic to measure the frame rate and yield at the end of the
131 + // frame. We start out assuming that we run at 30fps but then the
132 + // heuristic tracking will adjust this value to a faster fps if we get
133 + // more frequent animation frames.
134 + 33.33;
135 +
136 let prevRAFTime = -1;
137 let prevRAFInterval = -1;
138 let frameDeadline = 0;
@@ -199,31 +208,63 @@ if (
208 };
209
210 const performWorkUntilDeadline = () => {
202 - if (scheduledHostCallback !== null) {
203 - const currentTime = getCurrentTime();
204 - const hasTimeRemaining = frameDeadline - currentTime > 0;
205 - try {
206 - const hasMoreWork = scheduledHostCallback(
207 - hasTimeRemaining,
208 - currentTime,
209 - );
210 - if (!hasMoreWork) {
211 - scheduledHostCallback = null;
211 + if (enableMessageLoopImplementation) {
212 + if (scheduledHostCallback !== null) {
213 + const currentTime = getCurrentTime();
214 + // Yield after `frameLength` ms, regardless of where we are in the vsync
215 + // cycle. This means there's always time remaining at the beginning of
216 + // the message event.
217 + frameDeadline = currentTime + frameLength;
218 + const hasTimeRemaining = true;
219 + try {
220 + const hasMoreWork = scheduledHostCallback(
221 + hasTimeRemaining,
222 + currentTime,
223 + );
224 + if (!hasMoreWork) {
225 + isMessageLoopRunning = false;
226 + scheduledHostCallback = null;
227 + } else {
228 + // If there's more work, schedule the next message event at the end
229 + // of the preceding one.
230 + port.postMessage(null);
231 + }
232 + } catch (error) {
233 + // If a scheduler task throws, exit the current browser task so the
234 + // error can be observed.
235 + port.postMessage(null);
236 + throw error;
237 + }
238 + }
239 + // Yielding to the browser will give it a chance to paint, so we can
240 + // reset this.
241 + needsPaint = false;
242 + } else {
243 + if (scheduledHostCallback !== null) {
244 + const currentTime = getCurrentTime();
245 + const hasTimeRemaining = frameDeadline - currentTime > 0;
246 + try {
247 + const hasMoreWork = scheduledHostCallback(
248 + hasTimeRemaining,
249 + currentTime,
250 + );
251 + if (!hasMoreWork) {
252 + scheduledHostCallback = null;
253 + }
254 + } catch (error) {
255 + // If a scheduler task throws, exit the current browser task so the
256 + // error can be observed, and post a new task as soon as possible
257 + // so we can continue where we left off.
258 + port.postMessage(null);
259 + throw error;
260 }
213 - } catch (error) {
214 - // If a scheduler task throws, exit the current browser task so the
215 - // error can be observed, and post a new task as soon as possible
216 - // so we can continue where we left off.
217 - port.postMessage(null);
218 - throw error;
261 }
262 + // Yielding to the browser will give it a chance to paint, so we can
263 + // reset this.
264 + needsPaint = false;
265 }
221 - // Yielding to the browser will give it a chance to paint, so we can
222 - // reset this.
223 - needsPaint = false;
266 };
267
226 - // We use the postMessage trick to defer idle work until after the repaint.
268 const channel = new MessageChannel();
269 const port = channel.port2;
270 channel.port1.onmessage = performWorkUntilDeadline;
@@ -294,57 +335,66 @@ if (
335 prevRAFTime = rAFTime;
336 frameDeadline = rAFTime + frameLength;
337
338 + // We use the postMessage trick to defer idle work until after the repaint.
339 port.postMessage(null);
340 };
341
342 requestHostCallback = function(callback) {
343 scheduledHostCallback = callback;
302 - if (!isRAFLoopRunning) {
303 - // Start a rAF loop.
304 - isRAFLoopRunning = true;
305 - requestAnimationFrame(rAFTime => {
344 + if (enableMessageLoopImplementation) {
345 + if (!isMessageLoopRunning) {
346 + isMessageLoopRunning = true;
347 + port.postMessage(null);
348 + }
349 + } else {
350 + if (!isRAFLoopRunning) {
351 + // Start a rAF loop.
352 + isRAFLoopRunning = true;
353 + requestAnimationFrame(rAFTime => {
354 + if (requestIdleCallbackBeforeFirstFrame) {
355 + cancelIdleCallback(idleCallbackID);
356 + }
357 + if (requestTimerEventBeforeFirstFrame) {
358 + clearTimeout(idleTimeoutID);
359 + }
360 + onAnimationFrame(rAFTime);
361 + });
362 +
363 + // If we just missed the last vsync, the next rAF might not happen for
364 + // another frame. To claim as much idle time as possible, post a
365 + // callback with `requestIdleCallback`, which should fire if there's
366 + // idle time left in the frame.
367 + //
368 + // This should only be an issue for the first rAF in the loop;
369 + // subsequent rAFs are scheduled at the beginning of the
370 + // preceding frame.
371 + let idleCallbackID;
372 if (requestIdleCallbackBeforeFirstFrame) {
307 - cancelIdleCallback(idleCallbackID);
373 + idleCallbackID = requestIdleCallback(
374 + function onIdleCallbackBeforeFirstFrame() {
375 + if (requestTimerEventBeforeFirstFrame) {
376 + clearTimeout(idleTimeoutID);
377 + }
378 + frameDeadline = getCurrentTime() + frameLength;
379 + performWorkUntilDeadline();
380 + },
381 + );
382 }
383 + // Alternate strategy to address the same problem. Scheduler a timer
384 + // with no delay. If this fires before the rAF, that likely indicates
385 + // that there's idle time before the next vsync. This isn't always the
386 + // case, but we'll be aggressive and assume it is, as a trade off to
387 + // prevent idle periods.
388 + let idleTimeoutID;
389 if (requestTimerEventBeforeFirstFrame) {
310 - clearTimeout(idleTimeoutID);
311 - }
312 - onAnimationFrame(rAFTime);
313 - });
314 -
315 - // If we just missed the last vsync, the next rAF might not happen for
316 - // another frame. To claim as much idle time as possible, post a callback
317 - // with `requestIdleCallback`, which should fire if there's idle time left
318 - // in the frame.
319 - //
320 - // This should only be an issue for the first rAF in the loop; subsequent
321 - // rAFs are scheduled at the beginning of the preceding frame.
322 - let idleCallbackID;
323 - if (requestIdleCallbackBeforeFirstFrame) {
324 - idleCallbackID = requestIdleCallback(
325 - function onIdleCallbackBeforeFirstFrame() {
326 - if (requestTimerEventBeforeFirstFrame) {
327 - clearTimeout(idleTimeoutID);
390 + idleTimeoutID = setTimeout(function onTimerEventBeforeFirstFrame() {
391 + if (requestIdleCallbackBeforeFirstFrame) {
392 + cancelIdleCallback(idleCallbackID);
393 }
394 frameDeadline = getCurrentTime() + frameLength;
395 performWorkUntilDeadline();
331 - },
332 - );
333 - }
334 - // Alternate strategy to address the same problem. Scheduler a timer with
335 - // no delay. If this fires before the rAF, that likely indicates that
336 - // there's idle time before the next vsync. This isn't always the case,
337 - // but we'll be aggressive and assume it is, as a trade off to prevent
338 - // idle periods.
339 - let idleTimeoutID;
340 - if (requestTimerEventBeforeFirstFrame) {
341 - idleTimeoutID = setTimeout(function onTimerEventBeforeFirstFrame() {
342 - if (requestIdleCallbackBeforeFirstFrame) {
343 - cancelIdleCallback(idleCallbackID);
344 - }
345 - frameDeadline = getCurrentTime() + frameLength;
346 - performWorkUntilDeadline();
347 - }, 0);
396 + }, 0);
397 + }
398 }
399 }
400 };