Throttle
Implement a throttle function that takes a callback function and a delay time (in milliseconds) as arguments. The throttled function should ensure that the callback is executed at most once in the specified time period, regardless of how many times it's called.
Unlike debounce (which resets the timer with each call), throttle guarantees function execution at regular intervals while calls are being made.
Example
const throttledFn = throttle(() => console.log('Function called!'), 1000); // If called multiple times in quick succession throttledFn(); // Executes immediately throttledFn(); // Ignored throttledFn(); // Ignored // ... after 1000ms throttledFn(); // Executes throttledFn(); // Ignored
Constraints
- The function should execute immediately on the first call
- Subsequent calls within the delay period should be ignored
- After the delay period, the next call should execute immediately
- The throttled function should return the result of the callback function
Companies:
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
