Debounce
By Naga Sai Rao1 min read
Trailing Debounce
The function executes after the user stops triggering it for the specified delay.
text
function debounce(fn, delay){
let timer ;
return function(...args){
//['S']
console.log(Array.isArray(args) )
clearTimeout(timer);
timer = setTimeout(function(){
fn(...args)
},delay)
}
}
const debounceWrapper = debounce(searchFn,1000);
const searchInput = document.getElementById("searchBar");
searchInput.addEventListener("input",(event)=>{
const value = event.target.value;
debounceWrapper(value);
})
// SOAP
// one letter will get typed per 250 ms
// S - timer to
// SO - clear timer to and sets timer to t1
// SOA - clears timer t1 and sets timer to t2 - 750ms
// SOAP - clears timer t2 , set timer to t3 - 1000ms
// after 1000 i.e t3 search api will get hit to fetch resultsLeading Debounce
Sometimes you want the function to execute immediately on the first call, rather than waiting.
text
function leadingDebounce(fn,delay){
let timer ;
return function(...args){
if(!timer){
fn(...args);
}
clearTimeoout(timer);
timer = setTimeout(()=>{
timer = null
},delay)
}
}
// what happens if we dont clear timer in leading debounce ??
// delay assume 1000ms
// at 0ms first execution as there is no timer - creates a timer t0 with delay 1000ms
// at 500ms another click -as t0 exist function wont execute, would create another timer t1 with 1000ms
// at 1000ms t0 timer will set timer to null
// at 1100ms another click happened as timer is null execution happens
// leading debounce should delay next execution after first execution as long as activity exists , but here execution happens even with activity because we are not clearing timers, each activity in leading debounce should clear previous timer and sets a new one
N
Related
Lets Revise Javascript - 1
The JavaScript concepts interviewers use to make people fail: closures, this, prototypes, the event loop, coercion, and hoisting, with tricky output puzzles.
28 min read1
API Integration in JavaScript: Reading Responses, Handling Errors, and Stripe
Read API responses the right way: res.json() vs res.text(), error handling, timeouts, retries, React data fetching, and real Stripe payments and webhooks.
32 min read1
Next.js Caching in 2026: From the Four-Layer Model to use cache
A beginner-to-advanced guide to Next.js caching: the four cache layers, the RSC payload, Cache Components, and when revalidateTag beats updateTag.
35 min read1