tezvyn:

Track scroll depth: Intersection Observer vs scroll events

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

efficient scroll-depth tracking.

OUTLINE

place sentinels at depth thresholds and fire once via Intersection Observer, off the main thread; scroll listeners fire constantly and need throttling.

WHAT THIS TESTS: It evaluates whether you know the modern, performant way to detect scroll depth and can articulate concretely why it beats raw scroll listeners.

A GOOD ANSWER COVERS: Place lightweight sentinel markers in the DOM at the depth thresholds you care about, the twenty-five, fifty, seventy-five, and hundred percent points of the article. Register them with an Intersection Observer, which the browser evaluates asynchronously and off the main thread, invoking your callback only when a sentinel enters the viewport. Mark each milestone as fired once so you do not double-count, and record the deepest depth reached. For reporting, accumulate the reached milestones and send them in a batch using navigator.sendBeacon or a single request on pagehide rather than a network call per milestone, which keeps the system efficient across many concurrent clients.

THE COMPARISON: Scroll event listeners fire very frequently, many times per second during a flick, so you must throttle or debounce them, and inside the handler you typically read scrollTop and element offsets, which forces synchronous layout and can cause jank and battery drain if done carelessly. Intersection Observer inverts this: you declare what to watch and the thresholds, the browser does the geometry efficiently and notifies you only at crossings, with no throttling needed, no layout thrash, and simpler code overall.

LIKELY FOLLOW-UPS: How does Intersection Observer avoid layout thrashing under the hood. How do you ensure each milestone fires exactly once. How do you handle content that loads or resizes dynamically after the observer is set up. How do you batch and send the collected events efficiently.

ONE CONCRETE EXAMPLE: For a long article you inject four invisible divs at twenty-five, fifty, seventy-five, and hundred percent. An Intersection Observer watches them; as the reader scrolls past the halfway div it fires once, you record 'fifty percent reached,' and on pagehide a single beacon sends all reached milestones together, all without a single throttled scroll handler running on the main thread.

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.