Problem Statement
Standard debounce can potentially never execute if calls keep coming. In critical applications, we need a guarantee that the function will execute within a maximum time window. Implement a debounce with maxWait.
Requirements
Implement a debounce(func, wait, options) function where:
maxWait(number) - maximum time the function can be delayed- If maxWait is reached, function executes regardless of ongoing calls
- After maxWait execution, the cycle resets
- Standard debounce behavior applies within maxWait window
Example Usage
const sendAnalytics = (events) => {
console.log(`Sending ${events.length} events at ${Date.now()}`);
};
// Debounce 100ms, but guarantee execution every 1 second
const debouncedAnalytics = debounce(sendAnalytics, 100, { maxWait: 1000 });
// Continuous stream of events (every 50ms for 3 seconds)
let events = [];
const interval = setInterval(() => {
events.push({ type: "click", time: Date.now() });
debouncedAnalytics(events);
}, 50);
// Without maxWait: nothing would execute during the 3 seconds
// With maxWait: executes at ~1000ms, ~2000ms, and ~3100ms (after interval stops)
setTimeout(() => clearInterval(interval), 3000);Real-world Context
- Analytics event batching with SLA guarantees
- Real-time collaboration (periodic sync even during active editing)
- Progress indicators that must update within reasonable time
Follow-up Questions
- How does this interact with leading/trailing options?
- What's the relationship between wait and maxWait values?
- How would you test the maxWait behavior?