Skip to content

Commit

Permalink
feat(util): polyfil requestAnimationFrame, requestIdleCallbackFallback
Browse files Browse the repository at this point in the history
Special thanks to

Co-authored-by: Paul Irish <commits@paul.irish>
Co-authored-by: Merten van Gerven <merten.vg@gmail.com>
  • Loading branch information
3 people committed Feb 24, 2023
1 parent e5e13e2 commit 6dc4b73
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
2 changes: 2 additions & 0 deletions core/util/src/delay.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import {requestAnimationFrame} from './polyfill.js';

export const delay = (duration: number): Promise<void> => {
return new Promise((resolve) => setTimeout(resolve, duration));
};
Expand Down
1 change: 1 addition & 0 deletions core/util/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './delay.js';
export * from './json.js';
export * from './local-storage.js';
export * from './client-id.js';
export * from './polyfill.js';
26 changes: 26 additions & 0 deletions core/util/src/polyfill.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
interface IndexableWindow {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}

export const win = globalThis as IndexableWindow;

const requestAnimationFrameFallback = (callback: FrameRequestCallback): ReturnType<typeof setTimeout> =>
setTimeout(() => callback(Date.now()), 1000 / 60);

export const requestAnimationFrame: typeof globalThis.requestAnimationFrame =
win.requestAnimationFrame ||
win.webkitRequestAnimationFrame ||
win.mozRequestAnimationFrame ||
requestAnimationFrameFallback;

const requestIdleCallbackFallback = (
callback: () => void,
options?: IdleRequestOptions,
): ReturnType<typeof setTimeout> => setTimeout(callback, options?.timeout ?? 2000);

export const requestIdleCallback: typeof globalThis.requestIdleCallback =
win.requestIdleCallback ||
win.webkitRequestIdleCallback ||
win.mozRequestIdleCallback ||
requestIdleCallbackFallback;

0 comments on commit 6dc4b73

Please sign in to comment.