Skip to content

Commit

Permalink
Refactor the stopListening function
Browse files Browse the repository at this point in the history
  • Loading branch information
philipwalton committed Oct 15, 2024
1 parent 8e06644 commit 403cb79
Showing 1 changed file with 9 additions and 12 deletions.
21 changes: 9 additions & 12 deletions src/onLCP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,24 +88,21 @@ export const onLCP = (
// so the callback is run in a separate task to avoid extending the
// keyboard/click handler to reduce INP impact.
// https://github.com/GoogleChrome/web-vitals/issues/383
const stopListening = () =>
whenIdleOrHidden(
runOnce(() => {
if (!reportedMetricIDs[metric.id]) {
handleEntries(po!.takeRecords() as LCPMetric['entries']);
po!.disconnect();
reportedMetricIDs[metric.id] = true;
report(true);
}
}),
);
const stopListening = runOnce(() => {
if (!reportedMetricIDs[metric.id]) {
handleEntries(po!.takeRecords() as LCPMetric['entries']);
po!.disconnect();
reportedMetricIDs[metric.id] = true;
report(true);
}
});

// Stop listening after input or visibilitychange.
// Note: while scrolling is an input that stops LCP observation, it's
// unreliable since it can be programmatically generated.
// See: https://github.com/GoogleChrome/web-vitals/issues/75
for (const type of ['keydown', 'click', 'visibilitychange']) {
addEventListener(type, () => stopListening(), {
addEventListener(type, () => whenIdleOrHidden(stopListening), {
capture: true,
once: true,
});
Expand Down

0 comments on commit 403cb79

Please sign in to comment.