Skip to content

Instantly share code, notes, and snippets.

@luislobo14rap
Last active December 11, 2024 04:24
Show Gist options
  • Select an option

  • Save luislobo14rap/07080b40e22e95f160b1ec1b428623fb to your computer and use it in GitHub Desktop.

Select an option

Save luislobo14rap/07080b40e22e95f160b1ec1b428623fb to your computer and use it in GitHub Desktop.
throttle.js
// throttle.js v1
function throttle(func, wait) {
let wasCalled = false;
return function() {
if (!wasCalled) {
func();
wasCalled = true;
setTimeout(function() {
wasCalled = false;
}, wait);
}
};
};
// 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