Code

js/utils.js — debounce

In the code column — js/utils.js with the new debounce. The file already has date and text helpers (lessons 2, 4); now debounce joins them.

Read it closely — the whole trick is in three lines:

export function debounce(fn, delay = 250) {
  let timer;                                    // kept BETWEEN calls (a closure)
  return (...args) => {
    clearTimeout(timer);                        // cancel the previous schedule
    timer = setTimeout(() => fn(...args), delay);  // schedule a new one
  };
}

Two things worth understanding:

  • timer lives in a closure. debounce returns a function that "remembers" its timer between calls. Each keystroke sees the same timer and cancels it.
  • setTimeout returns an id, clearTimeout cancels it. If you cancel before delay elapses, the scheduled fn never runs. That's why, while typing fast, only the last one fires.

debounce is a general tool: it fits search, window resizing, autosave — anywhere events "rain down" often but you only want to react once things settle.

Tip. 250 ms is a good compromise for search: fast enough to feel instant, long enough to catch typing pauses. Server search often uses more (300–500 ms), UI buttons less. You tune it by feel.