Problem Statement
Some scenarios require guaranteed execution of the most recent call, even if it occurs during a throttle window. Implement a trailing-edge throttle that captures and executes the last call after the wait period.
Requirements
Implement a throttleTrailing(func, wait) function that:
- Does NOT execute immediately on the first call
- Queues the most recent call during the wait period
- Executes the queued call at the end of each wait period
- If no calls occur during a wait period, nothing executes
Example Usage
const updatePosition = (x, y) => {
console.log(`Position: (${x}, ${y})`);
};
const throttledUpdate = throttleTrailing(updatePosition, 100);
// Mouse moves rapidly
throttledUpdate(10, 20); // t=0ms → Queued
throttledUpdate(15, 25); // t=20ms → Replaces queue
throttledUpdate(20, 30); // t=50ms → Replaces queue
// t=100ms → Logs: "Position: (20, 30)"
throttledUpdate(25, 35); // t=120ms → Queued
throttledUpdate(30, 40); // t=150ms → Replaces queue
// t=200ms → Logs: "Position: (30, 40)"Visual Timeline
Calls: ▼ ▼ ▼ ▼ ▼
0 20 50 120 150 (ms)
|________| |_____|
Window 1 Window 2
Executes: ★ ★
↑ ↑
Trailing Trailing
(last value) (last value)Use Cases
- Syncing final position after drag operations
- Ensuring the last form state is saved
- Analytics that need the final interaction state
Follow-up Questions
- How would you handle arguments for the trailing call?
- What happens if the user stops interacting mid-window?