Facebook Pixel

Debounce Implementation: Step by Step

Step-by-step implementation of debounce with edge case handling.

Debounce Implementation: Step by Step

Step 1: Basic

function debounce(fn, delay) { let timer; return function () { clearTimeout(timer); timer = setTimeout(fn, delay); }; }

Step 2: Pass Arguments

function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; }

Step 3: Preserve this

function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; }

Step 4: Cancel Method

function debounce(fn, delay) { let timer; const debounced = function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; debounced.cancel = () => clearTimeout(timer); return debounced; }

Step 5: Immediate Flag

function debounce(fn, delay, immediate = false) { let timer; return function (...args) { clearTimeout(timer); if (immediate && !timer) fn.apply(this, args); timer = setTimeout(() => { timer = null; if (!immediate) fn.apply(this, args); }, delay); }; }

The Takeaway

Steps: basic (clear + set timer), pass args (rest/spread), preserve this (apply), add cancel method, and immediate flag (execute on first call, then debounce). Each step handles a real-world need.

Use rest parameters: return function(...args) { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }. Spread the args into the original function call.

Use apply: timer = setTimeout(() => fn.apply(this, args), delay). this inside the returned function is the caller's this. apply passes it to the original function.

Attach a cancel property to the returned function: debounced.cancel = () => clearTimeout(timer). Call debounced.cancel() to cancel the pending execution.

When true, the function executes on the first call (not waiting for the delay). Subsequent calls within the delay are debounced. Useful for buttons that should respond immediately but prevent double-clicks.

To reset the delay on each call. Without clearing, each call would set a new timer, and all would fire. Clearing ensures only the last call's timer runs.

Ready to master React 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.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.