Skip to content

Debounce & Throttle

  • ๐Ÿ‘‰ Ensures a function runs only after a certain delay since the last time it was called.
  • Eg:
function debounce(fn, delay){
let timer;
return function(...args){
clearTimeout(timer);
timer = setTimeout(()=> fn.apply(this, args), delay)
}
}
// Example: search bar
const search = debounce((query)=>{
console.log(`Searching for ${query}`)
}, 500)
search("s");
search("so");
search("sonam"); // โœ… Only "Searching for: sonam" runs after 500ms
  • โœ… Use case: Search box typing, window resize, API calls.
  • ๐Ÿ‘‰ Ensures a function run at most once in every given interval, no matter how many time itโ€™s triggered.
  • Eg:
function throttle(fn, interval){
let lastTime = 0;
return function (...args){
const now = Date.now()
if(now-lastTime >= interval){
lastTime = now;
fn.apply(this, args)
}
}
}
const handleScroll = throttle(()=>{
console.log(`Scroll event at: Date.now()`)
}, 1000)
window.addEventListener("scroll", handleScroll)
  • โœ… Use case: Scroll events, button clicks, drag & drop.
FeatureDebounceThrottle
DefinitionExecutes after user stops triggering for X msExecutes at fixed intervals
ExampleWait until user finishes typingRun once every second while scrolling
Best forAPI calls, searchScroll, resize, button spam protection
  • Debounce โ†’ โ€œWait until doneโ€.
  • Throttle โ†’ โ€œLimit how oftenโ€.