Last active
December 11, 2024 04:24
-
-
Save luislobo14rap/07080b40e22e95f160b1ec1b428623fb to your computer and use it in GitHub Desktop.
throttle.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // throttle.js v1 | |
| function throttle(func, wait) { | |
| let wasCalled = false; | |
| return function() { | |
| if (!wasCalled) { | |
| func(); | |
| wasCalled = true; | |
| setTimeout(function() { | |
| wasCalled = false; | |
| }, wait); | |
| } | |
| }; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // throttle.ts v2 | |
| type TUnknownFn = (...args: unknown[]) => void | |
| export function throttle(fn: TUnknownFn, delay: number): TUnknownFn { | |
| let wasCalled = false | |
| return (...args: unknown[]): void => { | |
| if (!wasCalled) { | |
| fn(...args) | |
| wasCalled = true | |
| setTimeout(() => { | |
| wasCalled = false | |
| }, delay) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment