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().