Merge "selenium: invoke jobs to enforce eventual consistency"
[lhc/web/wiklou.git] / resources / src / startup / mediawiki.requestIdleCallback.js
1 /* global mw */
2 ( function () {
3 var maxBusy = 50;
4
5 mw.requestIdleCallbackInternal = function ( callback ) {
6 setTimeout( function () {
7 var start = mw.now();
8 callback( {
9 didTimeout: false,
10 timeRemaining: function () {
11 return Math.max( 0, maxBusy - ( mw.now() - start ) );
12 }
13 } );
14 }, 1 );
15 };
16
17 /**
18 * Schedule a deferred task to run in the background.
19 *
20 * This allows code to perform tasks in the main thread without impacting
21 * time-critical operations such as animations and response to input events.
22 *
23 * Basic logic is as follows:
24 *
25 * - User input event should be acknowledged within 100ms per [RAIL].
26 * - Idle work should be grouped in blocks of upto 50ms so that enough time
27 * remains for the event handler to execute and any rendering to take place.
28 * - Whenever a native event happens (e.g. user input), the deadline for any
29 * running idle callback drops to 0.
30 * - As long as the deadline is non-zero, other callbacks pending may be
31 * executed in the same idle period.
32 *
33 * See also:
34 *
35 * - <https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback>
36 * - <https://w3c.github.io/requestidlecallback/>
37 * - <https://developers.google.com/web/updates/2015/08/using-requestidlecallback>
38 * [RAIL]: https://developers.google.com/web/fundamentals/performance/rail
39 *
40 * @member mw
41 * @param {Function} callback
42 * @param {Object} [options]
43 * @param {number} [options.timeout] If set, the callback will be scheduled for
44 * immediate execution after this amount of time (in milliseconds) if it didn't run
45 * by that time.
46 */
47 mw.requestIdleCallback = window.requestIdleCallback ?
48 // Bind because it throws TypeError if context is not window
49 window.requestIdleCallback.bind( window ) :
50 mw.requestIdleCallbackInternal;
51 // Note: Polyfill was previously disabled due to
52 // https://bugs.chromium.org/p/chromium/issues/detail?id=647870
53 // See also <http://codepen.io/Krinkle/full/XNGEvv>
54 }() );