CodeBlanks Logo Icon CodeBlanks

Summary - Performance

JavaScript course · Expert · Lesson 12/63

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.

Exercise 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.

Show example solution
memo = new Map(); inside run use has/get/set; wrapper uses clearTimeout then setTimeout.

Example solution:
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);
  };
}

Exercise 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().

Show example solution
Inside onScroll use Date.now() and now - lastRun >= interval; addEventListener("scroll") and return function cleanup() with removeEventListener.

Example solution:
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);
  };
}

Test yourself

  1. Read from cache

    const memo = new Map();
    const run = (q) => {
      if (memo.has(q)) return ____;
      const result = fetchFn(q);
      memo.set(q, result);
      return result;
    };
    Show 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;
    };
  2. Match each tool to its scenario

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

All lessons in Expert