It's a higher-order function and a closure: delayed(fn, ms) returns a new function, and that function remembers fn and ms. When the new function is called it calls setTimeout with a callback that runs fn. Two details show you understand it. Pass the arguments and this through: collect ...args and call fn.apply(this, args) from an arrow function, so the timer callback sees the caller's this. And remember each call schedules its own timer: three calls mean three runs. The follow-up is to make a new call reset the delay, which is debounce: keep the timer id in the closure and clearTimeout it before setting the next one.
How do you make a function that takes a callback function fn and returns a function that calls fn on a timeout?
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
The returned function closes over fn and ms. Each call sets one timer whose callback calls fn with the same arguments and this. The arrow function matters: it has no this of its own, so this inside it is the returned function's this (the object the method was called on). Nothing is scheduled until the returned function is called, and even a delay of 0 runs after the current code has finished.
// Returns a function; calling it schedules fn. The arrow function inside setTimeout keeps the// caller's `this` and arguments for when the timer fires.function delayed(fn, ms) {return function (...args) {setTimeout(() => fn.apply(this, args), ms);};}
passes 5 checks run on every build, against the native method where there is one
- fn runs after the delay, not before
- every call gets its own timer
- arguments and this are passed through
- creating the delayed function schedules nothing
- a delay of 0 still runs later, after the current code
A timer callback's return value goes nowhere, so the caller can't get fn's result. Returning a promise fixes that: it resolves with what fn returns and rejects if fn throws. cancel() on that promise clears the timer for that one call. A cancelled call's promise never settles, which is worth saying out loud: the alternative is to reject it with an abort error.
// Each call returns a promise for fn's result, with a cancel() for that one call.function delayed(fn, ms) {return function (...args) {let timer;const promise = new Promise((resolve) => {timer = setTimeout(resolve, ms);}).then(() => fn.apply(this, args)); // a throw inside fn becomes a rejectionpromise.cancel = () => clearTimeout(timer); // note: a cancelled call's promise never settlesreturn promise;};}
passes 9 checks run on every build, against the native method where there is one
- fn runs after the delay, not before
- every call gets its own timer
- arguments and this are passed through
- creating the delayed function schedules nothing
- a delay of 0 still runs later, after the current code
- the call returns a promise for fn's result
- a throw inside fn rejects the promise
- cancel stops that call only
- an async fn is awaited
Move the timer id out of the call and into the closure, so all calls share it, and clear it at the start of each call. Now only the last call in a burst survives, and fn runs once, ms after the calls stop. The last check runs the same three calls through both: delayed runs three times, debounce once.
// The follow-up: calling again resets the delay, so fn runs once, `ms` after the LAST call.// That is debounce.function debounce(fn, ms) {let timer;function debounced(...args) {clearTimeout(timer); // forget the call that was waitingtimer = setTimeout(() => fn.apply(this, args), ms);}debounced.cancel = () => clearTimeout(timer);return debounced;}function delayed(fn, ms) {return function (...args) {setTimeout(() => fn.apply(this, args), ms);};}
passes 6 checks run on every build, against the native method where there is one
- calling again resets the delay: one run, after the last call
- calls further apart than the delay each run
- the last call's this and arguments are used
- cancel drops the waiting call
- at most one timer is ever pending
- compared with delayed: the same three calls run three times
setTimeout itself
setTimeout(fn, delay, arg1, arg2) passes extra arguments to the callback, and the delay is a minimum, not a guarantee: the callback waits for the current code and anything queued before it.
Longer delays than asked for
Browsers clamp nested timers to at least 4 ms and throttle timers in background tabs, so a delayed function can run later than ms.
Debounced input handlers
Search-as-you-type and autosave wait until the user stops typing before doing the work, which is the advanced stage.
setTimeout(fn(), ms): that callsfnnow and schedules its return value.A regular
functionas the timer callback, whosethisisn't the caller's.Dropping the arguments, so
fnis always called with none.Calling
setTimeoutinsidedelayeditself instead of inside the returned function.For debounce, keeping the timer id inside the returned function, so each call has its own and nothing is ever reset.
Expecting the callback at exactly
ms: the delay is a minimum.
What is this inside the timer callback?
For a regular function passed to setTimeout, this is the global object (or undefined in strict mode and modules), not the object the method was called on. An arrow function takes this from where it was written, which is why the solution uses one.
How is debounce different from throttle?
Debounce waits for the calls to stop and runs once. Throttle runs at a steady maximum rate while the calls continue.
Does setTimeout(fn, 0) run immediately?
No. It queues a task that runs after the current code and after all pending microtasks (promise callbacks).
How would you cancel with an AbortSignal?
Listen for the signal's abort event, clear the timer there and reject the promise with signal.reason.
- developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
- developer.mozilla.org/en-US/docs/Web/API/Window/clearTimeout
- developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
- developer.mozilla.org/en-US/docs/Glossary/Debounce