How to Implement Debounce and Throttle from Scratch
How to build custom rate-limiting utilities to optimize performance and ace JS rounds.
Understand the Core Difference
Identify that Debounce delays execution until a period of inactivity passes (e.g., search type-ahead), while Throttle guarantees execution at regular intervals during a continuous event (e.g., window scrolling).
Write the Debounce Shell
Create a wrapper function that takes a callback function and a delay time as arguments. It must return a new inner function that preserves access to the outer variables via closures.
Track the Timer State
Declare a 'timeoutId' variable in the lexical scope of the parent wrapper function. This variable persists across multiple executions of the returned inner function.
Clear Active Timers
Inside the returned function, immediately call 'clearTimeout(timeoutId)'. This clears any previously scheduled execution if the user triggers the event again before the delay completes.
Schedule Execution Context
Reset the 'timeoutId' with a new 'setTimeout'. Inside the timeout callback, invoke the original function using '.apply(this, arguments)' to perfectly maintain the execution context and forward passing arguments.
Write the Throttle Shell
Create a wrapper function for throttle that accepts a function and a limit interval. Return a new inner function to handle incoming events.
Manage the Throttle Flag
Declare a boolean flag like 'isThrottling' in the parent lexical scope, initialized to false. This acts as a lock mechanism to ignore rapid successive calls.
Implement the Throttle Block
Inside the returned function, check if 'isThrottling' is true. If it is, return immediately or save the last call parameters depending on whether trailing execution is required.
Execute and Lock the Flag
If 'isThrottling' is false, execute the callback using '.apply(this, arguments)' immediately. Switch 'isThrottling' to true to prevent any other executions.
Reset the Throttle Lock
Set a 'setTimeout' for the specified limit duration. When the timer finishes, flip 'isThrottling' back to false, allowing the next natural event to pass through the wrapper.
Ready to master this completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

