Question presented to candidate: "You need to re-run a layout calculation whenever a specific div's size changes — maybe from a CSS container query, a font load, or a user dragging a resize handle. Would you poll getBoundingClientRect() in a requestAnimationFrame loop? What would you use instead?"
What a strong answer should cover:
- 📌 Interview term:
ResizeObserver— a real, built-in browser API that lets code.observe(element)and receive a real callback whenever that element's size genuinely changes — no polling loop, no manualrequestAnimationFrame-based checking required at all. - 📌 Interview term: the real, direct answer to the prompt — verified directly, live in a real browser (
ResizeObserveris genuinely NOT implemented in jsdom, confirmed directly —typeofis"undefined"there):ResizeObserver's callback genuinely fires ONCE immediately upon.observe(), reporting the element's real CURRENT size — even before any actual resize occurs — then fires AGAIN whenever the element's real size subsequently changes. - 📌 Interview term:
entry.contentRect— the real object each callback entry carries, giving the observed element's real, current width and height directly — no need to separately callgetBoundingClientRect()inside the callback at all. - 📌 Interview term:
.disconnect()— verified directly: calling it genuinely stops all future callbacks for every element that observer was watching, confirmed by a subsequent real resize producing no further callback. - A precise answer names the real performance advantage over polling: a
requestAnimationFrame-based polling loop runs on EVERY frame (up to 60 times per second) regardless of whether anything actually changed, genuinely wasting real CPU;ResizeObserver's callback fires ONLY when a real, actual size change genuinely occurs.
Clarifying questions expected:
- None — this is a definitional/practical question; directly demonstrating the real, verified fire-immediately-then-on-resize behavior is the strong signal.
Code / implementation expected: Yes — a real, live-browser-verified ResizeObserver observing an element through an initial callback, a real resize, and a .disconnect().