Interview questions
Implement debounce
A very common coding round: write a debounce utility.
Debounce delays running a function until a pause in calls — ideal for search-as-you-type or resize handlers, so you fire once the user stops rather than on every keystroke.
Debounce is an elevator door — every new person who steps in resets the "about to close" timer.
Key concepts
1
The implementation relies on a closure over a timer handle: each call clears the pending timer and schedules a new one, so only the final call in a burst actually runs.
closuretimer
2
Be ready to contrast it with throttle, which runs at most once per interval rather than waiting for silence.
throttle
javascript
function debounce(fn, delay = 300) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const onSearch = debounce((q) => fetchResults(q), 400);
input.addEventListener('input', (e) => onSearch(e.target.value));