CodeBlanks Logo Icon CodeBlanks

Summary - Performance

Build a search-input app using memoization, debounce and throttle.

Summary - Performance

In this group you learned four core performance tools: performance.now for measuring, memoization for caching, debounce for delaying, and throttle for rate-limiting.

You also saw how to keep timers and listeners clean to avoid memory leaks. Now you will combine these in a search input.

Practice Cached and debounced search

Write a function named createSearch. It takes fetchFn and delay and returns a cached, debounced search wrapper. Use a Map for the cache and setTimeout for the delay.

Starter code

script.js
// Build a debounced and cached search for a search input
// fetchFn and delay params; Map for cache, timer for delay

Sample solution

script.js
function createSearch(fetchFn, delay) {
  const memo = new Map();
  const run = (q) => {
    if (memo.has(q)) return memo.get(q);
    const result = fetchFn(q);
    memo.set(q, result);
    return result;
  };
  let timer = null;
  return function(query) {
    clearTimeout(timer);
    timer = setTimeout(() => run(query), delay);
  };
}

Practice Throttled scroll listener

Write a function named setupScroll. It takes handler and interval, sets up a throttled scroll listener, and returns a cleanup function named cleanup. Track time with Date.now().

Starter code

script.js
// Set up a throttled scroll listener and return a cleanup function
// handler and interval params; gate with lastRun, remove via cleanup

Sample solution

script.js
function setupScroll(handler, interval) {
  let lastRun = 0;
  const onScroll = () => {
    const now = Date.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      handler(now);
    }
  };
  window.addEventListener("scroll", onScroll);
  return function cleanup() {
    window.removeEventListener("scroll", onScroll);
  };
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Read from cache

Question
const memo = new Map();
const run = (q) => {
  if (memo.has(q)) return ____;
  const result = fetchFn(q);
  memo.set(q, result);
  return result;
};
Answer
const memo = new Map();
const run = (q) => {
  if (memo.has(q)) return memo.get(q);
  const result = fetchFn(q);
  memo.set(q, result);
  return result;
};

Explanation: On a hit you return memo.get(q) from the cache.

2 Match each tool to its scenario

Term Meaning
memoization expensive computation
debounce search box
throttle scroll event
cleanup remove listener

All lessons in Expert