Implement Throttle

MediumUtility Functions15 min4 tests

Implement a throttle function that ensures the provided function is called at most once per wait milliseconds.

Requirements

  • Execute the function immediately on the first call
  • Ignore subsequent calls within the wait period
  • After the wait period, allow the function to be called again

Example

const throttledFn = throttle(() => console.log('Scroll!'), 1000);
// Calling rapidly will only log once per second
Hints (5)
  1. Track the timestamp of the last execution.
  2. Compare current time with last execution time to decide whether to execute.
  3. Use Date.now() to get the current timestamp.
  4. Calculate the remaining wait time: wait - (now - lastTime)
  5. You may want to schedule a trailing call if the function is called during the wait period.

Topics

  • Utility Functions

Asked at

Google · Meta · LinkedIn · Airbnb

Loading the sandbox…

Join Us
blur