Promise Throttle
MediumPromises & Async20 min4 tests
Implement createThrottle(interval) that ensures a minimum gap of interval ms between starting each async task.
Requirements
add(asyncFn)— schedule an async function. Returns a promise that resolves with the function's result.- Tasks start in the order they are added.
- At least
intervalms must elapse between the start of consecutive tasks. - Tasks may overlap in execution (this is not a concurrency limit).
Example
const throttle = createThrottle(100);
throttle.add(async () => 'a'); // starts at t=0
throttle.add(async () => 'b'); // starts at t=100
throttle.add(async () => 'c'); // starts at t=200Hints (5)
- Track the timestamp of the last task start.
- Use a promise chain to serialize the scheduling of tasks.
- Before starting each task, check how much time has elapsed since the last start.
- If less than interval has elapsed, wait for the remaining time.
- Update lastStartTime to Date.now() right before executing the task.
Topics
- Promises & Async
Asked at
Google · Amazon · Stripe · Shopify
