How do you track impressions in an infinite feed with IntersectionObserver and sendBeacon?
IntermediateBrowser and web interview questionBy UIRound, updated 23 November 2026
Short answer
Watch every feed item with one shared IntersectionObserver. When an item crosses your visibility threshold, start a timer; if it stays visible for the dwell time, record one impression for that item id and never again. Queue impressions in memory, send them in batches, and flush the queue with navigator.sendBeacon when the page becomes hidden. A common definition is 50% visible for one continuous second, but it is a product decision.
Define an impression first
Before writing code, agree on what counts. Teams usually pick a visible fraction and a minimum continuous time on screen. "At least half of the item visible for at least one second" is a widely used convention, borrowed from how the online ad industry defines a viewable display ad. It is not a web standard, and a ranking team may want something different, such as a lower threshold for tall posts or a longer dwell for video.
Also decide:
- Whether time counts while the tab is hidden. It should not.
- Whether scrolling past quickly counts. With a dwell time, it does not.
- Whether an item seen twice in one session is one impression or two. Usually one.
One observer for the whole feed
Creating an observer per item is wasteful. One observer can watch thousands of targets; use entry.target to tell them apart and a data-id attribute to know which item it is.
const VISIBLE_RATIO = 0.5;
const DWELL_MS = 1000;
const seen = new Set(); // item ids already counted
const timers = new Map(); // item id -> pending dwell timer
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
const id = entry.target.dataset.id;
if (seen.has(id)) continue;
if (entry.intersectionRatio >= VISIBLE_RATIO) {
if (!timers.has(id) && document.visibilityState === "visible") {
timers.set(id, setTimeout(() => recordImpression(id, entry.target), DWELL_MS));
}
} else {
clearTimeout(timers.get(id));
timers.delete(id);
}
}
}, { threshold: VISIBLE_RATIO });
function recordImpression(id, el) {
timers.delete(id);
seen.add(id);
observer.unobserve(el); // counted once, stop watching
enqueue({ type: "impression", itemId: id, ts: Date.now() });
}The callback runs whenever an item's visible ratio crosses 0.5 in either direction, so the same handler starts the timer on the way in and cancels it on the way out. It also runs once for each item right after observe(), which covers items already on screen when the feed loads.
IntersectionObserver basics, including root, rootMargin and why it beats scroll listeners, are in what is IntersectionObserver used for.
Tall items and the threshold trap
A post taller than the viewport can never be 50% visible if 50% of it is more than the screen height. Handle that case by measuring how much of the viewport it fills instead:
const coversViewport = entry.intersectionRect.height >= entry.rootBounds.height * VISIBLE_RATIO;
const visibleEnough = entry.intersectionRatio >= VISIBLE_RATIO || coversViewport;If you use this rule, add more thresholds (for example [0, 0.25, 0.5, 0.75, 1]) so the callback runs often enough to notice it.
Pause when the page is hidden
The observer does not care whether the tab is in front. If the user switches tabs with an item on screen, its timer would complete and count an impression nobody saw. Cancel pending timers when the page hides, and let items that are still on screen restart their timers when it becomes visible again. The simplest way to restart is to unobserve and re-observe the uncounted items, since observe() delivers a fresh entry for each.
Infinite feeds and virtualised lists
New items are appended as the user scrolls. Call observer.observe(el) for each new node, and unobserve when a node is removed, or the observer keeps detached elements alive. In a virtualised list, DOM nodes are reused for different items, so key everything by the item id from data-id, never by the element. In React, observe in a ref callback or effect and clean up on unmount.
Batch the events
Sending one request per impression wastes battery and connections. Keep a queue and flush it when it reaches a size limit or after a short interval:
const queue = [];
let flushTimer;
function enqueue(event) {
queue.push(event);
if (queue.length >= 20) flush();
else flushTimer ??= setTimeout(flush, 5000);
}
function flush() {
clearTimeout(flushTimer);
flushTimer = undefined;
if (queue.length === 0) return;
const body = JSON.stringify({ events: queue.splice(0) });
const sent = navigator.sendBeacon("/analytics", body);
if (!sent) fetch("/analytics", { method: "POST", body, keepalive: true }).catch(() => {});
}Add a unique event id to each impression too, so the server can drop duplicates if a batch is retried. The coding questions an analytics SDK with batching and sendBeacon and a browser-side analytics delivery system go further with retries, sampling and offline queues.
Flush when the page hides, not on unload
The last moment you can reliably run code is when the page becomes hidden. On mobile, users often switch apps and the system later discards the tab without any further event. So flush on visibilitychange when the state is hidden, and also on pagehide as a backup:
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") flush();
});
addEventListener("pagehide", flush); // flush() is a no-op if the queue is emptyAvoid unload and beforeunload for this. They do not fire reliably on mobile, an unload handler can stop the page from entering the back/forward cache, and Chrome is phasing unload out. Practise the lifecycle events in Survive the back/forward cache.
navigator.sendBeacon(url, data) queues a small POST that the browser delivers even after the page is gone, without blocking navigation. It returns false if the browser refuses to queue it, usually because the payload is too large: the Fetch specification caps the total body size of in-flight keepalive requests, beacons included, at 64 KiB. Keep batches small, and flush often enough that the final batch fits. fetch with keepalive: true works the same way and lets you set headers.
A plain string body is sent as text/plain, which avoids a CORS preflight. If you send JSON as a Blob with type application/json to another origin, a preflight is needed; posting to the same origin, or a first-party subdomain proxy, avoids that problem.
Follow-up questions interviewers ask
Why not compute visibility with a scroll listener?
Scroll handlers run many times a second on the main thread and calling getBoundingClientRect() on every item forces layout work. The observer computes intersections as part of rendering and calls you only when a threshold is crossed. See log product impressions once scrolling stops for a scroll-based variant and its trade-offs.
Does IntersectionObserver know if the item is covered by a modal?
No. It measures geometry only. Chromium has an experimental extension, trackVisibility, that also checks whether the element is occluded or transformed, but it is not in other browsers. Most teams pause tracking while a modal or sheet is open.
How do you test impression tracking?
Unit-test the timer and dedupe logic with fake timers and a mocked observer that you trigger by hand. In an end-to-end test, scroll a real page and assert on the intercepted /analytics requests.
Should the client or the server dedupe?
Both. The client avoids sending duplicates in normal use. The server dedupes by event id, because retries, multiple tabs and flaky networks will still produce some.
Mistakes to avoid
One observer per item
Counting an impression the moment an item touches the viewport, with no threshold or dwell
Letting timers run while the tab is hidden
Keying impressions by DOM node in a virtualised list
Flushing in
unload, or sending a batch too large forsendBeaconto queue
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Log product impressions once scrolling stopsMedium35 min
- Implement an analytics SDK with event batching and
sendBeaconfallbackMedium45 minFree - Build a browser-side analytics delivery system with batching, sampling, offline queueing, and deduplicationHard75 min
- Build a serial analytics SDK that retries failed events in order and supports
flush()Medium30 min - Survive the back/forward cache: write
createPageLifecyclewithpagehide,pageshowandvisibilitychangeMedium30 min - Implement
useIntersectionObserver()for lazy loadingMedium35 min