Skip to content

Instantly share code, notes, and snippets.

@paullewis
Last active February 21, 2024 16:56
Show Gist options
  • Save paullewis/55efe5d6f05434a96c36 to your computer and use it in GitHub Desktop.
Save paullewis/55efe5d6f05434a96c36 to your computer and use it in GitHub Desktop.
Shims rIC in case a browser doesn't support it.
/*!
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* @see https://developers.google.com/web/updates/2015/08/using-requestidlecallback
*/
window.requestIdleCallback = window.requestIdleCallback ||
function (cb) {
return setTimeout(function () {
var start = Date.now();
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
}
});
}, 1);
}
window.cancelIdleCallback = window.cancelIdleCallback ||
function (id) {
clearTimeout(id);
}
@paullewis
Copy link
Author

This uses setTimeout as its fallback, because in lieu of requestIdleCallback you're most likely to just call your function immediately. Not ideal to redirect calls to setTimeout because it's not an API that will pick an idle time (which is why requestIdleCallback exists!).

This is a shim rather than an attempt at a polyfill because it's redirecting the call rather than making promises about behavior. Upside is this is Progressive Enhancement-friendly, and you can use this knowing that it will use full-fat requestIdleCallback when available, and when it's not it will schedule a task, which is no worse than what you would have had to do anyway. 👍

@piuccio
Copy link

piuccio commented Oct 21, 2015

Shouldn't timeRemaining return something close to 50? See question Is there maximum value that timeRemaining() will return? Yes, it’s currently 50ms.

@getify
Copy link

getify commented Oct 21, 2015

would it be better to try to use requestAnimationFrame(..) for the scheduling if available?

@paullewis
Copy link
Author

@piuccio I suspect you're right. At least that way there's some kind of deadline to work with. Though, as I think on it, if you call the shim back-to-back you're still going to be inside the same task loop / frame so it's probably as bad. That said, it's definitely closer to spec, so I updated it.

@getify possibly, although rAF may well be just as badly timed here as setTimeout. Let's say you do a rIC callback using rAF as the shim. Now you get rAF firing and you maybe run for 50ms (or longer) and you blow the frame budget. This, I guess, is why rIC exists at all. Us devs don't get enough info to make the decision as to the when, so we have to rely on the UA to tell us "now is a good time". Another thought here is that one should avoid DOM mutation in a rIC callback (fragments are a-ok) since DOM manipulation is far less deterministic than other ops, and you can end up forcing a sync layout and so on. Generally there's just no good way to genuinely shim rIC, so while I don't like setTimeout, all the other options are as ick.

@simevidas
Copy link

@paullewis Would it be possible for the timeRemaining method to dynamically compute a (somewhat useful) value? Something like:

window.requestIdleCallback = window.requestIdleCallback ||
  function (cb) {    
    var start = Date.now(); // ADDED
    return setTimeout(function () {
      cb({ 
        didTimeout: false,
        timeRemaining: function () {
          return 50 - (Date.now() - start); // ADDED
        }
      });
    }, 1);
  }

It seems to work relatively well:

capture

Note: The first number (20) is the timer id, so the while loop runs 6 times and then correctly ends after about 50 ms have passed.

@paullewis
Copy link
Author

@simevidas Great idea. Incorporated it, though I made sure it never goes < 0.

@igrigorik
Copy link

Should this be using performance.now() instead of Date.now? :)

@paullewis
Copy link
Author

@igrigorik Only supported as of iOS 9, which is just a touch too soon for my tastes on a shim. Bit of a shame, really.

@jcubic
Copy link

jcubic commented Dec 12, 2015

As this article says requestIdleCallback accept timeout option.

Copy link

ghost commented Mar 9, 2016

@getify rAF might still be better if the work to be done in the rIC happens to fit within a frame. Maybe using raf-timeout (an idea I'm experimenting with) with this rIC shim would help?

Copy link

ghost commented Mar 9, 2016

@paullewis I stumbled on requestIdleCallback because I'm working on a 3D engine at infamous.io. I'd like to be able to determine if there is time left in an rAF, and thought maybe rIC could be a way to put off some less-important rendering tasks. For example, maybe there's a primary animation, and a secondary animation, where the secondary animation can run at a slower fps if necessary, in order for the primary animation to be at 60 fps. If we call requestIdleCallback(..., {timeout:0}), will 0 for the timeout guarantee that the rIC fires after the next rAF, or can it skip an rAF even if the timeout is 0? This would be happening while the user is interacting; I'd still want to execute the logic after each frame, but I'd like to know if there's time left in the frame and rAF doesn't seem to give us that info.

Basically what I'm looking for is something like if (timeRemainingInRAF > 0) doMoreStuff(), or in english "if there's time remaining within the 16ms window of a 60fps loop...", and it seems like rIC is the only way to achieve this (although calculations in the rIC would be for the following rAF, which is fine). If there's some way to guarantee that we can fire an rIC with every rAF, then that would probably serve the purpose.

What exactly is deadline.timeRemaining? Is that the time remaining until the next vsync? The next rAF? The next what? The 50ms max timeRemaining hints that rIC is not necessarily the timeRemaining before the next rAF, which might mean rIC won't help me out.

The requestAnimationFrame API seems like it leaves me blind: I don't know how much time I have, therefore I don't know if my rendering calculations are taking too long, and I don't know how long they should take. The only thing I know is that the time I have for my rendering calculations is less than 16ms because the browser has to do it's own rendering stuff within those 16ms too.

@Krinkle
Copy link

Krinkle commented Mar 11, 2016

@paullewis Shouldn't start be set when the setTimeout callback runs rather than when it is scheduled?

 window.requestIdleCallback = window.requestIdleCallback ||
   function (cb) {
-    var start = Date.now();
     return setTimeout(function () {
+      var start = Date.now();
       cb({ 
         didTimeout: false,
         timeRemaining: function () {
           return Math.max(0, 50 - (Date.now() - start));
         }
       });
     }, 1);

See also wikimedia/mediawiki@55fc2a9#mediawiki.requestIdleCallback.js.

@chestozo
Copy link

chestozo commented Jan 20, 2017

@Krinkle it your version Date.now() inside cb will be the same as start.
Whereas here you have access to the start time before any idle callbacks were executed.

Basically in original version you can kind of limit idle period
whereas in your version you can only check execution time of individual idle callbacks:

https://developers.google.com/web/updates/2015/08/using-requestidlecallback

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment