In frontend development, some events — like typing, scrolling, or resizing — fire many times per second. If you're not careful, responding to each of these events individually can lead to laggy interfaces or unnecessary processing.
To avoid this, JavaScript developers use two smart techniques: debounce and throttle.
Let’s break down how each one works, where to use them, and see them in action with live StackBlitz demos.
⏱️ What is Debounce?
Debounce is a method that delays the execution of a function until a certain amount of time has passed since the last time the function was called.
Think of it as a “pause and wait” mechanism. If the event continues to fire (like keypresses), debounce will keep resetting the timer until the user stops.
📌 Example Use Case:
A search input where you don’t want to call the API on every keystroke, but only after the user pauses typing.
✅ Live Demo: Debounce
Try typing into the input field. The result only updates when you've stopped typing for 500ms:
🌀 What is Throttle?
Throttle limits how often a function is allowed to run, even if the event keeps firing.
Unlike debounce, throttle doesn’t wait for silence — it runs the function immediately and then ensures it doesn’t run again until the specified interval has passed.
📌 Example Use Case:
Tracking scroll position or mouse movements — where you want updates every few milliseconds, not continuously.
✅ Live Demo: Throttle
Scroll the embedded preview below. You’ll see the scroll position update no more than once every 300ms: