|
| 1 | +Implement a debounce function which accepts a callback function and a wait duration. Calling debounce() returns a function which has debounced invocations of the callback function |
| 2 | + |
| 3 | +```js |
| 4 | +function debounce(func: (...args: any[]) => void, wait: number): (...args: any[]) => void { |
| 5 | + let timeoutId: ReturnType<typeof setTimeout> | undefined; |
| 6 | + |
| 7 | + return function (...args: any[]) { |
| 8 | + if (timeoutId !== undefined) { |
| 9 | + clearTimeout(timeoutId); |
| 10 | + } |
| 11 | + |
| 12 | + timeoutId = setTimeout(() => { |
| 13 | + func.apply(this, args); |
| 14 | + }, wait); |
| 15 | + }; |
| 16 | +} |
| 17 | + |
| 18 | +// Example usage: |
| 19 | +const debouncedFunction = debounce(() => { |
| 20 | + console.log('Function executed!'); |
| 21 | +}, 1000); |
| 22 | + |
| 23 | +// Calling the debounced function multiple times within 1 second will only execute the callback once. |
| 24 | +debouncedFunction(); |
| 25 | +debouncedFunction(); |
| 26 | +debouncedFunction(); |
| 27 | +``` |
0 commit comments