Skip to the solution
MediumFrontendAsked in 20245 min read

Wire Up Debounced Resize and Throttled Scroll Handlers on a Real Component

3.9k views

The problem

Problem, as an interviewer would state it: "Attach a debounced resize listener and a throttled scroll listener to window, correctly clean them up, and explain why a naive attach-in-render approach breaks."

Examples:

Code
useEffect(() => {
  const onResize = debounce(() => recalcLayout(), 150);
  const onScroll = throttle(() => updateScrollProgress(), 100);
  window.addEventListener("resize", onResize);
  window.addEventListener("scroll", onScroll);
  return () => {
    window.removeEventListener("resize", onResize);
    window.removeEventListener("scroll", onScroll);
    onResize.cancel?.();
  };
}, []);

Clarifying questions expected:

  • Should the debounced/throttled wrapper be created ONCE and reused, or freshly created on every attach?
  • Does removeEventListener need the EXACT same function reference used in addEventListener?
  • What real cleanup, beyond removeEventListener, is needed on unmount?

Code / implementation expected: Yes — real, direct proof via a real jsdom window that rapid dispatched events produce exactly the expected number of real handler invocations, and that removal genuinely stops further ones.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof via jsdom: debounced resize and throttled scroll handlers fire the expected number of times, and cleanup genuinely stops them

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 49 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement pick(obj, paths) Supporting Both Shallow and Nested Paths

Continue