sr✳SHUBHAM RAJFRONTEND ENGINEER
FULL TECHNICAL GUIDEIntermediate3 min read

When should you use requestAnimationFrame?

Use requestAnimationFrame to schedule visual updates near the browser's next paint.

JavaScript#animation#performance
THE ANSWER / PLAIN ENGLISH

The idea to remember.

Use requestAnimationFrame to schedule visual updates near the browser's next paint. Cancel stale frames and respect reduced-motion preferences for long-running animation.

From first example to real project.

Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.

Basic: debounce after typing

01 / BEGINNER

Delay work until the user stops typing.

JAVASCRIPT / EXAMPLE
function debounce(fn, wait) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), wait);
  };
}

Intermediate: throttle frequent events

02 / INTERMEDIATE

Run periodic updates instead of handling every scroll event.

JAVASCRIPT / EXAMPLE
function throttle(fn, wait) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= wait) { last = now; fn(...args); }
  };
}

Real scenario: autocomplete input

03 / REAL SCENARIO

Debounce API work and encode user input safely.

JAVASCRIPT / EXAMPLE
const suggest = debounce(async term => {
  const response = await fetch('/api/suggest?q=' + encodeURIComponent(term));
  if (!response.ok) return;
  showSuggestions(await response.json());
}, 250);

Try it in your own words.

Explain when should you use requestAnimationFrame without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.

Keep learning here.

Explore more in-depth guides, exercises and related interview questions in this library.

Browse JavaScript study guides ↗
← Back to question library

Have something
in mind?

Start a conversation