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.
Debounce Implementation: Step by Step
Why do you need to clear the timer in debounce?
The answer
More FAQs in Debounce Implementation: Step by Step
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.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.