Description

In JavaScript, sometimes a function can be called too frequently, such as:

  • Input events while typing (oninput)
  • Window resizing (onresize)
  • Scroll events (onscroll)

Calling a function on every event can hurt performance. Debouncing is a technique that limits how often a function is executed.

A debounced function:

  • Waits for a delay after the last call.
  • Only executes the original function if no new calls happen within the delay.

Debouncing is widely used in search inputs, scroll handlers, and auto-saving forms.

Your Task

Write a function debounce(fn, delay) that:

  1. Accepts a function fn and a delay in milliseconds.
  2. Returns a new debounced function.
  3. Ensures fn is only called after the debounced function stops being called for the delay period.
  4. Passes all arguments and preserves the this context when calling fn.

Example

Input

function logMessage(message) {
console.log(message);
}

const debouncedLog = debounce(logMessage, 1000);

debouncedLog("Hello");
debouncedLog("Hello again");

Output

"Hello again" // Only logs once, 1000ms after the last call

Explanation

  • The first call is ignored because the second call happens before the 1000ms delay.
  • Only the last call within the delay period is executed.


Hints / How to Think About It
  • Use setTimeout to schedule the function call.
  • Keep track of a timeout ID to cancel the previous call if a new one happens within the delay.
  • Make sure to forward arguments and preserve this context using apply().
  • Think of debouncing as “wait until things settle down” before executing.