CodeZettaInterview Hub

JavaScript · Browser APIs · Mid-Level · Scenario

What problem does Intersection Observer solve, and how would you use it?

Short Interview Answer

It asynchronously notifies when elements enter/leave a viewport (or root), enabling lazy loading and infinite scroll without scroll listener jank.

Detailed Explanation

Scroll listeners that call `getBoundingClientRect` force layout frequently. IntersectionObserver runs off the main-thread-friendly observation path and delivers callbacks when thresholds cross. Use for image lazy-loading, infinite lists, ad viewability, and animation triggers. Remember to `unobserve`/`disconnect` on teardown. Root margins and thresholds tune prefetch distance. Pair with `loading="lazy"` where sufficient.

Example

const io = new IntersectionObserver((entries) => {
  for (const e of entries) {
    if (e.isIntersecting) loadMore();
  }
});
io.observe(sentinel);

Interview Tip

Contrast with scroll + layout thrashing.

Common Mistake

Forgetting to disconnect observers in SPAs (leaks).

Did you know this answer?