- Published on
Custom debounce function in JavaScript
- Authors
- Name
- Mrinmay Mukherjee
- @devmrin
Naive Implementation
const debounce = (func, delay) => {
let id;
return (...args)=>{
if(id) {
clearTimeout(id);
}
id = setTimeout(()=>{
func(...args);
}, delay)
}
}
What
In the debouncing technique, no matter how many times the user fires the event, the attached function will be executed only after the specified time once the user stops firing the event.
Why
Debouncing is used primarily for rate-limiting.
How
In our implementation, the debounce
function returns a debounced function. Which when called, will run only after the user specified delay
in miliseconds.
The way this works is, the first time when user calls our debounced function -
- We initialise our
setTimeout
call with the provideddelay
which immediately returns us anid
.
Every
setTimeout
returns anid
which is ofnumber
type. It's primarily used to clear any currently ongoingsetTimeout
by simply passing theid
toclearTimeout
function.
-
This
id
remains valid only until ourdelay
is elapsed. After which theid
becomesundefined
. -
Thus, on every single debounced function call we simply check if there is an
id
. -
If there is one, we clear our ongoing
setTimeout
call and re-initialise a newsetTimeout
call. -
Else, the
setTimeout
will run to completion and call our passed in functionfunc
after the specifieddelay
.