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 secondHints (5)
- Track the timestamp of the last execution.
- Compare current time with last execution time to decide whether to execute.
- Use
Date.now()to get the current timestamp. - Calculate the remaining wait time:
wait - (now - lastTime) - 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
