JavaScript Tutorial

Performance

Memory leaks, debouncing, throttling, and requestAnimationFrame

Why Performance Matters?

A slow web application leads to high bounce rates and poor user experience. In JavaScript, performance is not just about raw execution speed, but also about how efficiently you use the Event Loop, Call Stack, and System Memory.

1. Debouncing vs. Throttling

These are two essential techniques for handling "chatty" events like window resizing, scrolling, or real-time search inputs.
  • Debouncing: Wait until the user stops doing an action before running the code. (Best for a search input!)
  • Throttling: Limit how often the code can run, regardless of how fast the user is doing the action. (Best for scrolling!)
javascript
// A simple Debounce!
const debounce = (fn, delay) => {
    let timeoutId;
    return (...args) => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn(...args), delay);
    };
};

const sendSearch = debounce((q) => fetch(`/search?q=${q}`), 500);

2. Preventing Memory Leaks

A Memory Leak occurs when you create an object or a listener that is no longer needed but was never cleared, preventing it from being garbage collected.
Common causes:
  1. Global Variables: window.leak = "Everything";
  2. Dangling Listeners: Forgetting to use removeEventListener.
  3. Closures: Accidentally capturing a massive object in a function scope.
javascript
// CLEANUP: Always remove intervals/listeners!
const id = setInterval(updateUI, 1000);
// Later...
clearInterval(id);

3. High-Performance Animations: requestAnimationFrame

If you use setTimeout for animations, it won't be synced with the browser's refresh rate (60fps), leading to "jitter" or "tearing." requestAnimationFrame tells the browser exactly when to run your code for the smoothest possible animation.
javascript
function animate() {
    // Perform update logic!
    updatePosition();
    // Schedule the next frame!
    requestAnimationFrame(animate);
}

requestAnimationFrame(animate);

4. Web Workers (Parallel Processing)

The browser's main thread is the same thread that handles UI rendering and clicks. If you run a heavy math calculation there, the whole page will freeze. Use Web Workers to run that calculation in a separate background thread!
javascript
const worker = new Worker("worker.js");
worker.postMessage({ data: millionsOfNumbers });

Summary

TechniquePurposeBest Use Case...
DebounceWait for quiet periodSearch inputs, form validation
ThrottleLimit execution rateScroll, Window resize
RAFSmooth animationsGames, CSS transitions
WorkerParallel processingHeavy math, cryptography
Best ForSmooth UX, memory safety, speed
LighthouseStandard tool for measuring web performance
MemoryUse the "Performance" tab in DevTools to find leaks!
Optimizedv8 optimization can speed up common paths
BlockingNever block the main thread for >50ms
FragmentsUse DocumentFragment for batch DOM updates
CachingCache expensive function results (Memoization!)
Lazy LoadOnly load what's visible (Intersection Observer!)
Bundle SizeUse Tree Shaking to remove dead code!
DevToolsProfile your code to find bottle-necks
InteractionTarget the "First Input Delay" (FID) metric
Core Web VGoogle's metrics for a high-quality site
PriorityUse fetch priorities for critical assets
MinimizeRe-renders in frameworks like React
HardwareUse WebGL for GPU-accelerated graphics
NetworkUse compressed formats (Gzip/Brotli)
OfflineService Workers can cache assets for instant loads