Capítulo 164 de 411

Chapter 164: Debounced Resize Callback (Helper)

Core Idea

A helper that delays calling a function until window resizing has actually stopped for a short period, instead of firing on every single resize event (which fires many times per second while dragging).

Key Concepts

  • Wraps gsap.delayedCall() (paused, then restarted on each resize) as the debounce mechanism.
  • Default delay is 0.2 seconds after the last resize event.
  • Returns the event handler in case you want to removeEventListener it later.

Code Examples

function callAfterResize(func, delay) {
  let dc = gsap.delayedCall(delay || 0.2, func).pause(),
    handler = () => dc.restart(true);
  window.addEventListener("resize", handler);
  return handler;
}

callAfterResize(myFunction);
  • What it demonstrates: using a paused, restartable delayedCall as a debounce primitive instead of manual setTimeout bookkeeping.

Key Takeaways

  1. Avoids running expensive layout-recalculating logic (like ScrollTrigger.refresh()) on every resize tick.

Connects To

  • gsap.delayedCall(): the core API this helper is built on.
  • ScrollTrigger: a common reason to debounce resize handling, since refresh recalculates trigger positions.