Task: write debounce
Answer out loud or in your head first, then compare.
Answer
Debounce delays running a function until no further call arrives for a given time. Below is the trailing version, with no call at the start of a burst.
JavaScript
function debounce(fn, wait) {
let timer;
function wrapped(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
}
wrapped.cancel = () => clearTimeout(timer);
return wrapped;
}To be precise: a regular function keeps the caller's this; the timeout closes over the latest arguments. On cleanup I call cancel.
Pitfall: creating a new debounced function on every event means the timer can't be shared. This is the basic interview version, without leading, maxWait or returning a Promise.
How did it go? Be honest — “Not yet” puts the question on your review list.
Related questions
- What is event bubbling and throttling? — JavaScript
Practise in code
- Write debounce — runs tests in your browser