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 interval ms 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=200
Hints (5)
  1. Track the timestamp of the last task start.
  2. Use a promise chain to serialize the scheduling of tasks.
  3. Before starting each task, check how much time has elapsed since the last start.
  4. If less than interval has elapsed, wait for the remaining time.
  5. Update lastStartTime to Date.now() right before executing the task.

Topics

  • Promises & Async

Asked at

Google · Amazon · Stripe · Shopify

Join Us
blur