Problem Statement
A production-grade throttle should support both leading and trailing edge execution. This provides immediate response AND ensures the final state is captured. Implement a fully configurable throttle.
Requirements
Implement a throttle(func, wait, options) function where:
leading(boolean, default: true) - execute on leading edgetrailing(boolean, default: true) - execute on trailing edge- Both can be true simultaneously (default Lodash behavior)
- At least one must be true (validate this)
Example Usage
const track = (value) => console.log(`Value: ${value}`);
// Both edges (default) - most common in production
const bothThrottle = throttle(track, 100, { leading: true, trailing: true });
bothThrottle("a"); // t=0 → Logs "a" immediately
bothThrottle("b"); // t=30 → Queued
bothThrottle("c"); // t=60 → Replaces queue
// t=100 → Logs "c" (trailing)
// Leading only
const leadingThrottle = throttle(track, 100, { leading: true, trailing: false });
leadingThrottle("a"); // Logs immediately
leadingThrottle("b"); // Ignored
leadingThrottle("c"); // Ignored
// Nothing at t=100
// Trailing only
const trailingThrottle = throttle(track, 100, { leading: false, trailing: true });
trailingThrottle("a"); // Queued
trailingThrottle("b"); // Replaces queue
// t=100 → Logs "b"Behavior Matrix
| Leading | Trailing | First Call | End of Window |
|---|---|---|---|
| true | true | Executes | Executes (if queued) |
| true | false | Executes | Nothing |
| false | true | Queued | Executes |
| false | false | Invalid - throw error |
Follow-up Questions
- How does this compare to Lodash's throttle implementation?
- What edge cases exist when both options are true?