Create a function debounce that takes two arguments:
fn - the function to debounce.
delay - the number of milliseconds to wait before invoking fn.
The debounce function should return a new function that delays invoking fn until after delay milliseconds have passed since the last time the debounced function was called. This is useful to prevent a function from being called too frequently, such as on every keystroke or window resize event.
Example Inputs & Outputs
const debouncedLog = debounce(console.log, 300);
debouncedLog("Hello"); // waits 300ms
debouncedLog("Hi"); // resets timer
debouncedLog("Hey"); // resets timer again
// Only "Hey" will be logged after 300ms if no further calls are made
Constraints & Edge Cases
fn can be any callable function.
delay is a non-negative integer in milliseconds.
- The latest arguments to the debounced function should be used when
fn is eventually called.
- The
this context should be preserved.