raf.ts 733 B

123456789101112131415161718192021222324252627282930313233
  1. /**
  2. * requestAnimationFrame polyfill
  3. */
  4. import { isServer } from './index';
  5. let prev = Date.now();
  6. /* istanbul ignore next */
  7. function fallback(fn: FrameRequestCallback): number {
  8. const curr = Date.now();
  9. const ms = Math.max(0, 16 - (curr - prev));
  10. const id = setTimeout(fn, ms);
  11. prev = curr + ms;
  12. return id;
  13. }
  14. /* istanbul ignore next */
  15. const root = <Window>(isServer ? global : window);
  16. /* istanbul ignore next */
  17. const iRaf = root.requestAnimationFrame || fallback;
  18. /* istanbul ignore next */
  19. const iCancel = root.cancelAnimationFrame || root.clearTimeout;
  20. export function raf(fn: FrameRequestCallback): number {
  21. return iRaf.call(root, fn);
  22. }
  23. export function cancel(id: number) {
  24. iCancel.call(root, id);
  25. }