Write a debounce function from scratch.
A debounce needs one piece of state, which is the pending timer, and two actions. It has to cancel the pending call when a new one arrives, and it has to schedule the real call when the calls stop.
function debounce(fn, waitMs) {
var timer = null;
function debounced() {
var args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
timer = null;
fn.apply(null, args);
}, waitMs);
}
return debounced;
}
// Try it.
function log(value) {
console.log('called with', value);
}
var debounced = debounce(log, 30);
debounced('a');
debounced('b');
debounced('c');
// Only "c" is logged, 30ms after the last call.Passing the arguments along matters. The debounced function accepts whatever you give it and forwards the arguments from the final call, which is what you want for a search box, because the last keystroke is the one that counts. The this binding is another detail worth getting right, because a debounced method still needs its receiver, and using fn.apply(null, args) keeps the call simple and predictable.
Notice that the timer is set back to null inside the callback. Without that line the function would still hold the number of a timer that has already fired, and the next cancel would try to clear a timer that no longer exists. It is harmless, but it is untidy, and it shows that you are comfortable with the timer API.
That is the whole implementation. It is about fifteen lines long, and it is a good question because it tests whether you understand the timer API, closures, and the difference between scheduling work and cancelling it.