# Performance Optimization

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Performance Optimization
Source: https://www.devtutorials.ai/learn/javascript/performance/performance-optimization

> Debounce for search boxes, API calls and form input; throttle for scroll, mouse-move and click events; memoization for caching the results of slow, repeated calculations; and how to choose between them.

## What Is Performance Optimization?

**Performance optimization** = making a program skip work it does not need, so it feels fast. Often the slow part is a function that runs **too often**.

- **Debounce:** wait until activity stops, then run once.
- **Throttle:** run at most once per set period.
- **Memoization:** remember a result, so the same calculation is not repeated.

**Simple lesson:** run less often, and still give the right result.

### A Real-World Example

Typing "laptop" in a shop's search box fires 6 events, but only the last search matters: **debounce** sends 1 request.
Scrolling fires dozens of events a second; **throttle** checks the "back to top" button a few times a second.
The price table formats the same prices again and again; **memoization** works each one out once.

<figure className="ts-fig">
  <svg viewBox="0 0 560 190" role="img" aria-label="Eight event ticks on three rows. Debounce fires once after the last tick. Throttle fires on ticks 1, 4 and 7. Memo shows a cache hit for a repeated input." width="100%">
    <rect x="0" y="0" width="560" height="190" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <text x="16" y="30" fontSize="12" fill="#475569">events</text>
    <g fill="#94a3b8"><rect x="110" y="20" width="6" height="16" /><rect x="150" y="20" width="6" height="16" /><rect x="190" y="20" width="6" height="16" /><rect x="230" y="20" width="6" height="16" /><rect x="270" y="20" width="6" height="16" /><rect x="310" y="20" width="6" height="16" /><rect x="350" y="20" width="6" height="16" /><rect x="390" y="20" width="6" height="16" /></g>
    <text x="16" y="80" fontSize="12" fill="#1e40af">debounce</text>
    <circle cx="470" cy="76" r="9" fill="#2563eb"><animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.6;0.7;1" dur="3s" repeatCount="indefinite" /></circle>
    <text x="490" y="80" fontSize="11" fill="#1e40af">once, after</text>
    <text x="16" y="130" fontSize="12" fill="#166534">throttle</text>
    <circle cx="113" cy="126" r="9" fill="#16a34a" /><circle cx="233" cy="126" r="9" fill="#16a34a" /><circle cx="353" cy="126" r="9" fill="#16a34a" />
    <text x="16" y="175" fontSize="12" fill="#854d0e">memoize</text>
    <rect x="110" y="160" width="120" height="22" rx="4" fill="#fef3c7" stroke="#d97706" /><text x="170" y="175" textAnchor="middle" fontSize="11" fill="#92400e">fib(25): compute</text>
    <rect x="250" y="160" width="140" height="22" rx="4" fill="#dcfce7" stroke="#16a34a" /><text x="320" y="175" textAnchor="middle" fontSize="11" fill="#166534">fib(25): from cache</text>
  </svg>
  <figcaption>Same burst of events: debounce runs once, throttle samples, memoize reuses answers.</figcaption>
</figure>

These boxes simulate bursts of events with short waits. `Date.now()` is frozen here so dates stay correct, so the timers use `performance.now()`, which keeps ticking.

## What You Will Learn

1. Debounce: what, why, how, and for search, APIs and input.
2. Throttle: what, why, how, and for scroll, mouse move and clicks.
3. Memoization: caching results with a `Map`, and safe keys.
4. When to pick each one, and how they combine.

## Debounce

### What is debouncing?

**Debouncing** = wait until a burst of calls stops, then run once. Each new call **restarts** the wait. Like a lift door that waits again whenever someone walks in.

**Why "debounce"?** A physical button "bounces" and sends several signals; debouncing keeps one.

```js runnable title="Four keystrokes, one search"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

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

const search = debounce((query) => {
  console.log(`search runs for: "${query}"`);
}, 200);

for (const query of ["A", "As", "Ash", "Asha"]) {
  console.log(`typed: "${query}"`);
  search(query);
  await sleep(50); // keys pressed 50ms apart
}

await sleep(400); // the user stops typing
```

Expected output:

```text
typed: "A"
typed: "As"
typed: "Ash"
typed: "Asha"
search runs for: "Asha"
```

### Why debouncing is needed

Typing, resizing and dragging fire many events a second; usually only the final value matters.

```js runnable title="Counting requests with and without debounce"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

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

let plainRequests = 0;
let debouncedRequests = 0;

const plainSearch = () => plainRequests++;
const debouncedSearch = debounce(() => debouncedRequests++, 200);

for (const query of ["l", "la", "lap", "lapt", "lapto", "laptop"]) {
  plainSearch(query);
  debouncedSearch(query);
  await sleep(40);
}

await sleep(400);
console.log("requests without debounce:", plainRequests);
console.log("requests with debounce:   ", debouncedRequests);
```

Expected output:

```text
requests without debounce: 6
requests with debounce:    1
```

### How debouncing works

The debounced function keeps one **timer** (`setTimeout`). Every call cancels the old timer and starts a new one.

```js runnable title="Watching the timer being cancelled and restarted"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function debounceWithLog(fn, wait) {
  let timer = null;
  return (...args) => {
    if (timer !== null) console.log("  cancelled the waiting call");
    clearTimeout(timer);
    console.log(`  started a new ${wait}ms wait for "${args[0]}"`);
    timer = setTimeout(() => {
      timer = null;
      fn(...args);
    }, wait);
  };
}

const save = debounceWithLog((text) => console.log(`saved: "${text}"`), 200);

save("Hel");
await sleep(50);
save("Hello");
await sleep(400);
```

Expected output:

```text
  started a new 200ms wait for "Hel"
  cancelled the waiting call
  started a new 200ms wait for "Hello"
saved: "Hello"
```

Create the debounced function **once**, outside the handler. Calling `debounce(fn, 200)` inside the handler makes a fresh timer each time, so nothing is debounced.

### Debouncing a search box

The search runs once, for the finished word, instead of flashing results for half-typed ones.

```js runnable title="A debounced search over a product list"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

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

const productNames = ["Monitor", "Mouse", "Keyboard", "Monitor Stand", "Webcam"];

const searchProducts = debounce((query) => {
  const matches = productNames.filter((name) =>
    name.toLowerCase().includes(query.toLowerCase())
  );
  console.log(`results for "${query}":`, matches.join(", "));
}, 200);

for (const query of ["m", "mo", "mon"]) {
  searchProducts(query);
  await sleep(60);
}

await sleep(400);
```

Expected output:

```text
results for "mon": Monitor, Monitor Stand
```

A real input box: type, and the search runs when you pause.

```dom runnable title="Type in the box: the search runs when you pause"
<label for="search">Search products</label>
<input id="search" placeholder="Try typing monitor">
<p id="status">Nothing searched yet.</p>
<script>
  function debounce(fn, wait) {
    let timer;
    return (...args) => {
      clearTimeout(timer);
      timer = setTimeout(() => fn(...args), wait);
    };
  }

  const productNames = ["Monitor", "Mouse", "Keyboard", "Monitor Stand", "Webcam"];
  const status = document.querySelector("#status");
  let searchCount = 0;

  const runSearch = debounce((query) => {
    searchCount += 1;
    const matches = productNames.filter((name) =>
      name.toLowerCase().includes(query.toLowerCase())
    );
    status.textContent = `Search #${searchCount} for "${query}": ${matches.join(", ") || "no matches"}`;
    console.log(status.textContent);
  }, 300);

  document.querySelector("#search").addEventListener("input", (event) => {
    runSearch(event.target.value);
  });
</script>
```

### Debouncing API calls

**API call** = a request to a server: slow, and often limited or paid. This box uses a `data:` URL so no internet is needed.

```js runnable title="One API request for a whole burst of typing"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

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

let requestCount = 0;

const lookUpCity = debounce(async (city) => {
  requestCount++;
  console.log(`request #${requestCount} sent for "${city}"`);
  const body = JSON.stringify({ city, deliveryDays: 2 });
  const response = await fetch("data:application/json," + encodeURIComponent(body));
  const result = await response.json();
  console.log("response:", result);
}, 200);

for (const city of ["Che", "Chen", "Chenn", "Chennai"]) {
  lookUpCity(city);
  await sleep(50);
}

await sleep(500);
```

Expected output:

```text
request #1 sent for "Chennai"
response: {
  "city": "Chennai",
  "deliveryDays": 2
}
```

### Debouncing user input

Autosave after each pause in typing. Two bursts give two saves.

```js runnable title="Autosave: a pause in the middle produces two saves"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

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

const autosave = debounce((text) => console.log(`saved draft: "${text}"`), 200);

// First burst of typing
for (const text of ["Dear", "Dear Ravi", "Dear Ravi,"]) {
  autosave(text);
  await sleep(50);
}

await sleep(400); // the user stops to think

// Second burst of typing
for (const text of ["Dear Ravi, thanks", "Dear Ravi, thanks for the order."]) {
  autosave(text);
  await sleep(50);
}

await sleep(400);
```

Expected output:

```text
saved draft: "Dear Ravi,"
saved draft: "Dear Ravi, thanks for the order."
```

### Cases

- **Search as you type:** search once the user pauses.
- **Autosave:** save a moment after typing stops.
- **Form validation:** check a username once it is fully typed.
- **Window resize:** recalculate the layout once, at the end.
- **Address auto-suggest:** one lookup for the finished street name.

## Throttle

### What is throttling?

**Throttling** = run at most once per period. The first call runs at once; calls during the period are ignored. Like a bus that leaves every 15 minutes.

**Why "throttle"?** An engine throttle limits how much fuel flows in.

```js runnable title="Eight events, and a function allowed to run once every 150ms"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function throttle(fn, interval) {
  let lastRun = -Infinity;
  return (...args) => {
    const now = performance.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      fn(...args);
    }
  };
}

const ranFor = [];
const update = throttle((eventNumber) => ranFor.push(eventNumber), 150);

for (let eventNumber = 1; eventNumber <= 8; eventNumber++) {
  update(eventNumber);
  await sleep(60); // an event every 60ms
}

console.log("events fired:", 8);
console.log("function ran for events:", ranFor.join(", "));
```

Expected output:

```text
events fired: 8
function ran for events: 1, 4, 7
```

### Why throttling is needed

Scrolling and mouse moves fire constantly; a few updates a second are plenty.

```js runnable title="Handler runs with and without throttle"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function throttle(fn, interval) {
  let lastRun = -Infinity;
  return (...args) => {
    const now = performance.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      fn(...args);
    }
  };
}

let plainRuns = 0;
let throttledRuns = 0;
const onScrollPlain = () => plainRuns++;
const onScrollThrottled = throttle(() => throttledRuns++, 150);

for (let i = 0; i < 8; i++) {
  onScrollPlain();
  onScrollThrottled();
  await sleep(60);
}

console.log("handler runs without throttle:", plainRuns);
console.log("handler runs with throttle:   ", throttledRuns);
```

Expected output:

```text
handler runs without throttle: 8
handler runs with throttle:    3
```

### How throttling works

It remembers when it last ran (`performance.now()`, milliseconds since the page started):

- Enough time passed? Run, and record the time.
- Not enough? Ignore the call.

```js runnable title="Watching each call being allowed or ignored"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function throttleWithLog(fn, interval) {
  let lastRun = -Infinity;
  return (...args) => {
    const now = performance.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      console.log(`call ${args[0]}: allowed`);
      fn(...args);
    } else {
      console.log(`call ${args[0]}: ignored, too soon`);
    }
  };
}

const track = throttleWithLog(() => {}, 150);

for (let callNumber = 1; callNumber <= 4; callNumber++) {
  track(callNumber);
  await sleep(60);
}
```

Expected output:

```text
call 1: allowed
call 2: ignored, too soon
call 3: ignored, too soon
call 4: allowed
```

`lastRun` starts at `-Infinity`, so the first call is always allowed.

`performance.now()` is also better in real code: it is not affected by changes to the computer's clock.

### Throttling scroll events

In a browser:

```js
window.addEventListener("scroll", throttle(updateBackToTopButton, 150));
```

This box has no page to scroll, so it sends simulated positions:

```js runnable title="Simulated scrolling, checked a few times per second"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function throttle(fn, interval) {
  let lastRun = -Infinity;
  return (...args) => {
    const now = performance.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      fn(...args);
    }
  };
}

const checkBackToTop = throttle((scrollY) => {
  const showButton = scrollY >= 400;
  console.log(`scrollY ${scrollY}: button ${showButton ? "shown" : "hidden"}`);
}, 150);

for (let scrollY = 0; scrollY <= 700; scrollY += 100) {
  checkBackToTop(scrollY);
  await sleep(60);
}
```

Expected output:

```text
scrollY 0: button hidden
scrollY 300: button hidden
scrollY 600: button shown
```

### Throttling mouse move events

A tooltip that follows the pointer still follows the same path, with fewer updates.

```js runnable title="Simulated mouse movement, sampled at a steady rate"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function throttle(fn, interval) {
  let lastRun = -Infinity;
  return (...args) => {
    const now = performance.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      fn(...args);
    }
  };
}

const moveTooltip = throttle((x, y) => {
  console.log(`tooltip moved to (${x}, ${y})`);
}, 150);

const pointerPath = [
  [10, 20], [30, 25], [50, 30], [70, 40],
  [90, 45], [110, 50], [130, 60], [150, 65],
];

for (const [x, y] of pointerPath) {
  moveTooltip(x, y);
  await sleep(60);
}
```

Expected output:

```text
tooltip moved to (10, 20)
tooltip moved to (70, 40)
tooltip moved to (130, 60)
```

### Throttling frequent click events

A triple-click on **Place order** becomes one order.

```js runnable title="Three quick clicks place one order"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function throttle(fn, interval) {
  let lastRun = -Infinity;
  return (...args) => {
    const now = performance.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      fn(...args);
    }
  };
}

let ordersPlaced = 0;
const placeOrder = throttle(() => {
  ordersPlaced++;
  console.log(`order #${ordersPlaced} placed`);
}, 500);

// A nervous triple-click
placeOrder();
await sleep(40);
placeOrder();
await sleep(40);
placeOrder();

// A genuine second order, much later
await sleep(700);
placeOrder();

console.log("clicks: 4, orders placed:", ordersPlaced);
```

Expected output:

```text
order #1 placed
order #2 placed
clicks: 4, orders placed: 2
```

For payment buttons, also disable the button while the request runs. Throttle stops fast repeats; disabling stops clicks during a slow request.

## Memoization

### What is memoization?

**Memoization** = save a call's result; the next call with the same input returns the saved answer. **Why "memo"?** A short note so you need not remember.

```js runnable title="The second call with the same input is answered from the cache"
const shippingCache = new Map();

function shippingCost(weightKg) {
  if (shippingCache.has(weightKg)) {
    console.log(`${weightKg}kg: answered from the cache`);
    return shippingCache.get(weightKg);
  }
  console.log(`${weightKg}kg: calculating...`);
  const cost = 5 + weightKg * 2.5;
  shippingCache.set(weightKg, cost);
  return cost;
}

console.log("cost:", shippingCost(4));
console.log("cost:", shippingCost(4));
console.log("cost:", shippingCost(10));
```

Expected output:

```text
4kg: calculating...
cost: 15
4kg: answered from the cache
cost: 15
10kg: calculating...
cost: 30
```

### Why memoization is needed

A slow function called again and again with the same input wastes time. Only memoize a **pure function**: same input, same result, no outside changes.

```js runnable title="Counting how many times the slow work really runs"
let calculations = 0;

function countPrimesBelow(limit) {
  calculations++;
  let count = 0;
  for (let n = 2; n < limit; n++) {
    let isPrime = true;
    for (let d = 2; d * d <= n; d++) {
      if (n % d === 0) { isPrime = false; break; }
    }
    if (isPrime) count++;
  }
  return count;
}

const cache = new Map();
function countPrimesBelowMemo(limit) {
  if (!cache.has(limit)) cache.set(limit, countPrimesBelow(limit));
  return cache.get(limit);
}

for (let i = 0; i < 5; i++) countPrimesBelowMemo(10000);

console.log("answer:", countPrimesBelowMemo(10000));
console.log("calls: 6, calculations run:", calculations);
```

Expected output:

```text
answer: 1229
calls: 6, calculations run: 1
```

### How memoization works

A wrapper keeps a `Map` in a closure. On each call:

1. Build a **key** from the input.
2. If the cache has it, return the stored answer.
3. If not, call the real function, store the answer, return it.

```js runnable title="A reusable memoize wrapper"
function memoize(fn) {
  const cache = new Map();
  return (input) => {
    if (cache.has(input)) return cache.get(input);
    const result = fn(input);
    cache.set(input, result);
    return result;
  };
}

let runs = 0;
function squareArea(side) {
  runs++;
  return side * side;
}

const fastSquareArea = memoize(squareArea);

for (const side of [3, 5, 3, 5, 3]) {
  console.log(`side ${side}: area ${fastSquareArea(side)}`);
}
console.log("real function ran:", runs, "times");
```

Expected output:

```text
side 3: area 9
side 5: area 25
side 3: area 9
side 5: area 25
side 3: area 9
real function ran: 2 times
```

### Caching function results

For several arguments, build the key from all of them: `JSON.stringify(args)` gives `"[1299,10]"`.

```js runnable title="A key built from every argument"
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      console.log(`  cache hit for ${key}`);
      return cache.get(key);
    }
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}

function discountedPrice(price, percentOff) {
  return price - (price * percentOff) / 100;
}

const cachedDiscount = memoize(discountedPrice);

console.log("1299 at 10% off:", cachedDiscount(1299, 10));
console.log("1299 at 50% off:", cachedDiscount(1299, 50));
console.log("1299 at 10% off:", cachedDiscount(1299, 10));
```

Expected output:

```text
1299 at 10% off: 1169.1
1299 at 50% off: 649.5
  cache hit for [1299,10]
1299 at 10% off: 1169.1
```

A cache grows with every new input. For user input, like search words, give it a size limit.

### Avoiding repeated calculations

Recursive Fibonacci repeats the same small steps thousands of times. Memoized, each value is worked out once.

```js runnable title="Fibonacci, counting every call"
let plainCalls = 0;
function fib(n) {
  plainCalls++;
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);
}

let memoCalls = 0;
const fibCache = new Map();
function fibMemo(n) {
  memoCalls++;
  if (n < 2) return n;
  if (fibCache.has(n)) return fibCache.get(n);
  const result = fibMemo(n - 1) + fibMemo(n - 2);
  fibCache.set(n, result);
  return result;
}

console.log("fib(25):     ", fib(25), "after", plainCalls, "calls");
console.log("fibMemo(25): ", fibMemo(25), "after", memoCalls, "calls");
```

Expected output:

```text
fib(25):      75025 after 242785 calls
fibMemo(25):  75025 after 49 calls
```

### Performance optimization using memoization

Timing with `performance.now()`. Exact numbers depend on the computer; the gap is the point.

```js runnable varies title="Timing fib(30) with and without memoization"
function fib(n) {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);
}

const fibCache = new Map();
function fibMemo(n) {
  if (n < 2) return n;
  if (fibCache.has(n)) return fibCache.get(n);
  const result = fibMemo(n - 1) + fibMemo(n - 2);
  fibCache.set(n, result);
  return result;
}

let start = performance.now();
fib(30);
const plainMs = performance.now() - start;

start = performance.now();
fibMemo(30);
const memoMs = performance.now() - start;

console.log("plain:   ", plainMs.toFixed(2), "ms");
console.log("memoized:", memoMs.toFixed(2), "ms");
console.log("memoized was faster:", memoMs < plainMs);
```

Memoizing a function that is already fast can make it slower. Measure first.

## Comparison and usage

### Debounce vs throttle

Debounce runs once **after** the burst; throttle runs **during** it at a steady rate.

```js runnable title="The same eight events through debounce and throttle"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

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

function throttle(fn, interval) {
  let lastRun = -Infinity;
  return (...args) => {
    const now = performance.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      fn(...args);
    }
  };
}

const debouncedRuns = [];
const throttledRuns = [];
const debounced = debounce((n) => debouncedRuns.push(n), 200);
const throttled = throttle((n) => throttledRuns.push(n), 150);

for (let eventNumber = 1; eventNumber <= 8; eventNumber++) {
  debounced(eventNumber);
  throttled(eventNumber);
  await sleep(60);
}
await sleep(400);

console.log("debounce ran for:", debouncedRuns.join(", "));
console.log("throttle ran for:", throttledRuns.join(", "));
```

Expected output:

```text
debounce ran for: 8
throttle ran for: 1, 4, 7
```

| | Debounce | Throttle |
|---|---|---|
| Runs | once, after the calls stop | at most once per period, while calls continue |
| Uses | the last value | a steady sample of values |
| Good for | search, autosave, validation, resize | scroll, mouse move, repeated clicks |

### Debounce vs memoization

Debounce controls **when** a function runs; memoization controls **whether** the work is redone. They combine well:

```js runnable title="Debounce skips the keystrokes; memoization skips the repeat search"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

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

function memoize(fn) {
  const cache = new Map();
  return (input) => {
    if (!cache.has(input)) cache.set(input, fn(input));
    return cache.get(input);
  };
}

const productNames = ["Desk", "Desk Lamp", "Desk Mat", "Designer Chair", "Monitor"];
let searchesRun = 0;

const findProducts = memoize((query) => {
  searchesRun++;
  return productNames.filter((name) => name.toLowerCase().startsWith(query));
});

const onType = debounce((query) => {
  console.log(`"${query}":`, findProducts(query).join(", "));
}, 200);

const bursts = [["d", "de", "des", "desk"], ["des"], ["desk"]];
for (const burst of bursts) {
  for (const query of burst) {
    onType(query);
    await sleep(50);
  }
  await sleep(400);
}

console.log("keystrokes: 6, searches run:", searchesRun);
```

Expected output:

```text
"desk": Desk, Desk Lamp, Desk Mat
"des": Desk, Desk Lamp, Desk Mat, Designer Chair
"desk": Desk, Desk Lamp, Desk Mat
keystrokes: 6, searches run: 2
```

### When to use debounce

Only the final value matters, and the user pauses when done:

- Search boxes and auto-suggest lists.
- Autosaving forms and documents.
- Checking a username or email.
- Recalculating layout after a resize.

### When to use throttle

You need regular updates while something is still happening:

- Showing or hiding a button while scrolling.
- Moving a tooltip or dragged item.
- Stopping repeat clicks on order or send buttons.
- Steady progress or analytics updates.

### When to use memoization

A pure function is slow and gets the same inputs again and again:

- Recursive calculations like Fibonacci.
- Formatting values that repeat, like prices in a table.
- Filtering or sorting with a query already tried.

Never memoize a function that reads the time, uses random numbers, or changes things outside itself.

## Performance on a Web Page

A product search that is **debounced** (runs when you pause) and **memoized** (a repeated query is answered from the cache). The Console counts both.

```js runnable preview="product-list" title="A debounced, memoized product search"
const PRODUCTS = ["Desk", "Desk Lamp", "Desk Mat", "Designer Chair", "Steel bottle", "Lunch box", "Notebook"];
const list = document.querySelector("#products");
const status = document.querySelector("#status");
let searchesRun = 0;
let keystrokes = 0;

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

function memoize(fn) {
  const cache = new Map();
  return (key) => {
    if (!cache.has(key)) cache.set(key, fn(key));
    return cache.get(key);
  };
}

const search = memoize((query) => {
  searchesRun += 1;
  return PRODUCTS.filter((p) => p.toLowerCase().includes(query.toLowerCase()));
});

const show = debounce((query) => {
  const results = search(query);
  list.innerHTML = results.map((r) => `<li>${r}</li>`).join("");
  status.textContent = `${results.length} found`;
  console.log(`keystrokes: ${keystrokes}, real searches: ${searchesRun}`);
}, 300);

document.querySelector("#search").addEventListener("input", (event) => {
  keystrokes += 1;
  show(event.target.value);
});
show("");
```

Type `desk` quickly, delete a letter, retype it. Many keystrokes, few searches, and the repeat `desk` comes from the cache.

**Easy way to remember:** **debounce** = wait for quiet, **throttle** = steady beat, **memoize** = write it down.

## TL;DR

- Debounce: restart a timer on each call; run once after the burst.
- Throttle: allow one run per period; ignore the rest.
- Memoize pure functions with a `Map` and a key from every argument.
- Create debounced/throttled functions once, outside handlers.
- Limit cache size, and measure before optimizing.

## Try this

In **What is throttling?**, change `150` to `250`. More events fall inside each period, so fewer event numbers appear in the output.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `debounce(...)` inside the handler | It still debounces | Create it once, outside | Every keystroke runs |
| Debounce for scroll | Any limiter works | Throttle for steady updates | The button appears only after stopping |
| Key from the first argument only | One argument is enough | Key from all: `JSON.stringify(args)` | Wrong cached answers |
| Memoizing an impure function | Caching is always safe | Only pure functions | Stale values |
| An unlimited cache | Memory is free | Limit or clear it | Memory keeps growing |
| `Date.now()` in these boxes | It ticks | It is frozen here; use `performance.now()` | The throttle never runs again |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `clearTimeout(timer); timer = setTimeout(run, wait)` | the heart of debounce: cancel the waiting call, then start a new wait |
| `debounce(fn, 300)` | runs `fn` once, 300ms after the last call, with the last arguments |
| `performance.now() - lastRun >= interval` | the heart of throttle: has the period passed since the last run? |
| `throttle(fn, 150)` | runs `fn` at most once every 150ms while calls continue |
| `const cache = new Map()` | stores saved results, one entry per key |
| `cache.has(key)` / `cache.get(key)` / `cache.set(key, value)` | check, read and save a cached result |
| `JSON.stringify(args)` | a cache key built from every argument |
| `memoize(fn)` | returns a version of `fn` that calculates each input once |

</div>

## Exercises

## What to Remember

- Do less work, not faster work.
- Debounce for "when done", throttle for "while happening".
- Memoize slow, pure, repeated calculations.

Next: **Array and String Method Cheat Sheet**. Every array and string method from this course, in one place, each with a Try button.
