KatInterview

Build a Quiet-Period Call Delayer in JavaScript

Data Structure DesignModel answer
MediumModel answerData Structure Designjavascriptclosurestimers

Last updated

Write a higher-order function that postpones a callback until calls have stopped for a given time, preserving this and arguments, and discuss cancel, flush and leading-edge variants.

Delay Until Calls Go Quiet

Write a function debounce(func, delay) that wraps func and returns a new function. The wrapper must not run func right away. Instead, func should run only once the wrapper has gone delay milliseconds without being called. Every new call to the wrapper during that waiting period discards the pending run and restarts the countdown.

Requirements

  • The wrapper must preserve the this value it was called with, so it works when attached to an object as a method.
  • Every argument given to the wrapper must be passed on to func.
  • When several calls happen in quick succession, func must run only once, using the context and arguments of the final call.

Signature

/**
 * @param {Function} func - The function to wrap.
 * @param {number} delay - Quiet period in milliseconds.
 * @return {Function} - The wrapped function.
 */
function debounce(func, delay) {
  // your implementation
}

Example

const greet = debounce(() => console.log('Hello!'), 1000);
greet();
greet();
// 'Hello!' is printed once, about 1000 ms after the second call.

Constraints

  • delay is a non-negative integer.
  • func may be an anonymous function or a method that belongs to an object.

Things to address in your answer

  • What should the wrapper return, given that func runs later? Explain the trade-off.
  • Show that a burst of rapid calls cannot cause more than one execution.
  • Describe how you would extend the design (for example cancelling, flushing, or running on the leading edge).

Explain your approach, state the time and space complexity, and give the code.

Hints

Hint 1

You need state that survives between calls but is private to each wrapped function. Think about what a closure can hold, and what handle you get back when you schedule a timer.

Hint 2

Before scheduling a new run, cancel the one that is already pending. That guarantees at most one live timer at any moment.

Hint 3

Pay attention to which kind of function you use at each level. The returned wrapper needs its own dynamic `this`, while the timer callback needs to reuse the wrapper's `this` and arguments. Rest parameters plus `apply` handle forwarding.