|
| 1 | +```js |
| 2 | +function throttle(func, wait) { |
| 3 | + if (typeof func !== 'function') { |
| 4 | + throw new TypeError('Expected a function'); |
| 5 | + } |
| 6 | + |
| 7 | + let isThrottled = false; // A flag to track whether the function is throttled |
| 8 | + |
| 9 | + return function (...args) { |
| 10 | + const context = this; // Preserve `this` context for the callback |
| 11 | + |
| 12 | + if (!isThrottled) { |
| 13 | + // If not throttled, invoke the callback |
| 14 | + func.apply(context, args); |
| 15 | + |
| 16 | + // Set the throttling state to true |
| 17 | + isThrottled = true; |
| 18 | + |
| 19 | + // Reset the throttling state after the wait duration |
| 20 | + setTimeout(() => { |
| 21 | + isThrottled = false; |
| 22 | + }, wait); |
| 23 | + } |
| 24 | + }; |
| 25 | +} |
| 26 | +``` |
| 27 | +### Explanation |
| 28 | +#### Validate Input: |
| 29 | +The function checks whether the provided func is a valid function using typeof. If not, it throws a TypeError. |
| 30 | + |
| 31 | +#### Tracking Throttle State: |
| 32 | +A flag `(isThrottled)` is used to determine if the function is currently throttled. When the function is invoked, the flag is set to true, preventing further calls to func until the wait time expires. |
| 33 | + |
| 34 | +#### Return the Throttled Function: |
| 35 | +The throttle function returns a new function. The returned function: |
| 36 | + |
| 37 | +* Checks the `isThrottled` flag. If false, it immediately invokes the callback function (func) using func.apply(context, args) to maintain the correct this context and arguments. |
| 38 | +* Sets the `isThrottled` flag to true to start throttling. |
| 39 | +* Uses `setTimeout` to reset the isThrottled flag back to false after the specified wait duration. |
| 40 | + |
| 41 | +### Example |
| 42 | +```js |
| 43 | +import throttle from './throttle'; |
| 44 | + |
| 45 | +function logMessage(message) { |
| 46 | + console.log(`Logged: ${message}`); |
| 47 | +} |
| 48 | + |
| 49 | +const throttledLog = throttle(logMessage, 2000); // Throttle with 2000ms wait time |
| 50 | + |
| 51 | +// Simulate rapid calls |
| 52 | +throttledLog('Hello!'); |
| 53 | +throttledLog('Hello again!'); |
| 54 | +throttledLog('Hello one more time!'); |
| 55 | + |
| 56 | +// Output: |
| 57 | +// "Logged: Hello!" (immediately) |
| 58 | +// No other calls invoke the callback for the next 2000ms |
| 59 | +``` |
0 commit comments