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:
- Accepts a function fnand a delay in milliseconds.
- Returns a new debounced function.
- Ensures fnis only called after the debounced function stops being called for the delay period.
- Passes all arguments and preserves the thiscontext when callingfn.
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 setTimeoutto 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 thiscontext usingapply().
- Think of debouncing as “wait until things settle down” before executing.
