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:
timerlives in a closure.debouncereturns a function that "remembers" itstimerbetween calls. Each keystroke sees the sametimerand cancels it.setTimeoutreturns an id,clearTimeoutcancels it. If you cancel beforedelayelapses, the scheduledfnnever 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.