Debounce & Throttle
๐น 1. Debounce
Section titled โ๐น 1. Debounceโ- ๐ 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.
๐น 2. Throttle
Section titled โ๐น 2. Throttleโ- ๐ 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.
๐น Key Difference
Section titled โ๐น Key Differenceโ| Feature | Debounce | Throttle |
|---|---|---|
| Definition | Executes after user stops triggering for X ms | Executes at fixed intervals |
| Example | Wait until user finishes typing | Run once every second while scrolling |
| Best for | API calls, search | Scroll, resize, button spam protection |
๐ Formula to remember:
Section titled โ๐ Formula to remember:โ- Debounce โ โWait until doneโ.
- Throttle โ โLimit how oftenโ.