Debounce
Create a function debounce that takes two arguments:
fn- the function to debounce.delay- the number of milliseconds to wait before invokingfn.
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
fncan be any callable function.delayis a non-negative integer in milliseconds.- The latest arguments to the debounced function should be used when
fnis eventually called. - The
thiscontext should be preserved.
Companies:
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
