Problem Statement
As a Staff Engineer, you're reviewing a PR where a junior engineer used debounce for a scroll handler. Walk through your decision framework for choosing between throttle and debounce, and implement both to demonstrate the difference.
Requirements
Implement both functions and create a demonstration that clearly shows:
- How throttle guarantees regular execution during continuous input
- How debounce waits for input to stop
- Visual output showing execution timing for both
Example Implementation
// Your implementations
function throttle(func, wait) { /* ... */ }
function debounce(func, wait) { /* ... */ }
// Demonstration
function runComparison() {
const events = [];
const start = Date.now();
const logThrottle = throttle((v) => {
events.push({ type: "throttle", time: Date.now() - start, value: v });
}, 100);
const logDebounce = debounce((v) => {
events.push({ type: "debounce", time: Date.now() - start, value: v });
}, 100);
// Simulate 500ms of continuous input (every 30ms)
let value = 0;
const interval = setInterval(() => {
value++;
logThrottle(value);
logDebounce(value);
}, 30);
setTimeout(() => {
clearInterval(interval);
// Wait for debounce to complete
setTimeout(() => {
console.table(events);
/*
Expected output:
| type | time | value |
|----------|------|-------|
| throttle | 0 | 1 |
| throttle | 100 | 4 |
| throttle | 200 | 7 |
| throttle | 300 | 10 |
| throttle | 400 | 14 |
| throttle | 500 | 17 |
| debounce | 600 | 17 | ← Only fires once, after input stops!
*/
}, 150);
}, 500);
}Decision Framework
| Use Throttle When | Use Debounce When |
|---|---|
| You need regular updates during activity | You only care about final state |
| User expects visual feedback during action | User expects action after they stop |
| Examples: scroll position, resize, drag | Examples: search input, form validation |
Follow-up Questions
- How would you explain this to a junior engineer in a code review?
- Are there cases where you might use both together?
- How do you handle edge cases in animations/games?