-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
52 lines (47 loc) · 1.54 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*! next.js MIT https://raw.githubusercontent.com/vercel/next.js/dd7a54c5099c781273b01f97788e980fd203e188/license.md */
// ref: https://github.com/vercel/next.js/blob/dd7a54c5099c781273b01f97788e980fd203e188/packages/next/client/request-idle-callback.ts
type RequestIdleCallbackHandle = any;
type RequestIdleCallbackOptions = {
timeout: number;
};
type RequestIdleCallbackDeadline = {
readonly didTimeout: boolean;
timeRemaining: () => number;
};
declare global {
interface Window {
requestIdleCallback: (
callback: (deadline: RequestIdleCallbackDeadline) => void,
opts?: RequestIdleCallbackOptions
) => RequestIdleCallbackHandle;
cancelIdleCallback: (id: RequestIdleCallbackHandle) => void;
}
}
export const requestIdleCallback =
(typeof self !== 'undefined' &&
self.requestIdleCallback &&
self.requestIdleCallback.bind(window)) ||
function (
cb: (deadline: RequestIdleCallbackDeadline) => void
): NodeJS.Timeout {
const start = Date.now();
return setTimeout(() => {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
},
});
}, 1);
};
export const cancelIdleCallback =
(typeof self !== 'undefined' &&
self.cancelIdleCallback &&
self.cancelIdleCallback.bind(window)) ||
function (id: RequestIdleCallbackHandle): void {
return clearTimeout(id);
};
if (typeof window !== 'undefined') {
window.requestIdleCallback = requestIdleCallback;
window.cancelIdleCallback = cancelIdleCallback;
}