Loading...
Loading...
In modern web applications, certain events (like window resizing, search input, or button clicks) can fire dozens of times per second. Executing expensive operations on every single event is highly inefficient. A debounce function solves this by ensuring that a given function is only called after a specified delay has elapsed since the last time it was invoked.
Implement a debounce(fn, delay) function from scratch in JavaScript. The debounced function should:
fn by delay milliseconds after the last call.fn to be called with the correct arguments and this context after the delay.Input:
fn — A function to debounce.delay — A non-negative integer representing the delay in milliseconds.Output:
fn is only called once after delay ms have passed since the last invocation.If a debounced function with delay = 300 is called at t=0ms and t=100ms, fn should only execute once at approximately t=400ms (100ms + 300ms).
If the debounced function is called only once, fn executes after delay ms with the correct arguments.
If the debounced function is called 5 times rapidly in succession (within the delay window), fn executes only once — after the delay from the last call.
timerId (the return value of setTimeout).clearTimeout(timerId) to cancel any pending timer, then setTimeout to schedule a new one.fn.apply(this, arguments) inside the setTimeout callback to ensure the original function receives the correct this context and all arguments.0 <= delay <= 10000 (milliseconds) fn is a valid JavaScript function The debounced function may be called 0 or more times Arguments passed to the debounced function must be forwarded to fn The correct this context must be preserved
0/**
* @param {Function} fn
* @param {number} delay
* @return {Function}
*/
function debounce(fn, delay) {
// Your implementation here
}