-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
86 lines (80 loc) · 2.45 KB
/
index.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Global requestId returned by requestIdleCallback
let requestIdleId = 0;
let requestAnimationId = 0;
let frozenDurationInMs = 0;
/**
* @see https://github.com/buildwithflux/log-time-to-next-idle
*/
function logTimeToNextIdle(name, callback, options) {
if (
typeof window === "undefined" ||
!window.requestIdleCallback ||
!window.requestAnimationFrame
) {
return;
}
options = {
warnOnConcurrent: true,
frozenSuffix: "_frozen",
maxTimeInMs: 10000,
minTimeInMs: 10,
...options,
};
const startMarkName = `${name}_start`;
window.performance.mark(startMarkName);
// setTimeout takes care of the possibilty that the idle callback somehow
// fires before the interaction effects have started. 10ms should be long
// enough for any effect to start in a new task.
setTimeout(() => {
// Cancel existing requests to keep to model of single user input, single UI response
if (requestIdleId || requestAnimationId) {
cancelIdleCallback(requestIdleId);
cancelAnimationFrame(requestAnimationId);
options.warnOnConcurrent &&
// eslint-disable-next-line no-console
console.warn(
startMarkName + " is displacing an exisiting idle callback"
);
}
requestAnimationId = requestAnimationFrame(() => {
const measure = window.performance.measure(
`${name}${options.frozenSuffix}`,
startMarkName
);
// NOTE: FF and Safari don't support
if (!measure) return;
frozenDurationInMs = Math.round(measure.duration);
requestAnimationId = 0;
});
requestIdleId = requestIdleCallback(
({ didTimeout }) => {
const endMarkName = `${name}_end`;
window.performance.mark(endMarkName);
const measure = window.performance.measure(
`${name}`,
startMarkName,
endMarkName
);
// NOTE: FF and Safari don't support
if (!measure) return;
const durationInMs = Math.round(measure.duration);
if (callback) {
callback(name, {
durationInMs,
frozenDurationInMs,
didTimeout,
});
} else {
console.info(
`${name} took ${frozenDurationInMs}ms until unfrozen, ${durationInMs}ms until idle`
);
}
requestIdleId = 0;
},
{
timeout: options.maxTimeInMs,
}
);
}, options.minTimeInMs);
}
exports.logTimeToNextIdle = logTimeToNextIdle;