Debouncing vs Throttling in JavaScript

Day 20/100 of JavaScript Today’s topic : Debouncing vs Throttling Both are techniques used to control how frequently a function executes, especially during high-frequency events like typing, scrolling, or resizing 🔹Debouncing Executes the function only after a delay once the event stops firing function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } 👉 Use case: Search input 🔹Throttling Executes the function at a fixed interval while the event is happening function throttle(fn, limit) { let lastCall = 0; return function (...args) { const now = Date.now(); if (now - lastCall >= limit) { lastCall = now; fn.apply(this, args); } }; } 👉 Use case: Scroll events ❕Difference - Debounce → waits for pause - Throttle → runs at intervals Debouncing reduces unnecessary calls by waiting, while throttling ensures controlled execution over time — both improve performance and user experience #Day20 #JavaScript #100DaysOfCode

To view or add a comment, sign in

Explore content categories