Skip to content

Instantly share code, notes, and snippets.

@fr-ser
Last active July 15, 2023 15:12
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fr-ser/ded7690b245223094cd876069456ed6c to your computer and use it in GitHub Desktop.
Save fr-ser/ded7690b245223094cd876069456ed6c to your computer and use it in GitHub Desktop.
Typed debounce function wtih TypeScript
export function debounce<F extends Function>(func:F, wait:number):F {
let timeoutID:number;
if (!Number.isInteger(wait)) {
console.warn("Called debounce without a valid number")
wait = 300;
}
// conversion through any necessary as it wont satisfy criteria otherwise
return <any>function(this:any, ...args: any[]) {
clearTimeout(timeoutID);
const context = this;
timeoutID = window.setTimeout(function() {
func.apply(context, args);
}, wait);
};
};
@iheidari
Copy link

iheidari commented Sep 4, 2019

When I tried to use it, I've got this error:

C:...\src\util\performance.ts: Unexpected token (11:2)

9 | // conversion through any necessary as it wont satisfy criteria otherwise
10 | return (function(this: any, ...args: any[]) {

11 | clearTimeout(timeoutID);
| ^
12 | const context = this;
13 |
14 | timeoutID = window.setTimeout(function() {

Any idea?

So I use debounce from https://github.com/chodorowicz/ts-debounce
and everything is fine.

@fr-ser
Copy link
Author

fr-ser commented Sep 5, 2019

Nope. Works for me. What version of typescript are you using and what compiler (settings)?

@iheidari
Copy link

iheidari commented Sep 6, 2019

I use Gatsby to create my project. When I run it or build, everything is fine.
But this error happen when I wanna run storybook and webpack complain about this.

  • OS: Windows 10
  • TS version: 3.6.2
  • Gatsby: 2.14.6
  • Storybook: 5.1.11
  • Webpack(storybook built-in): 4.39.3

@fr-ser
Copy link
Author

fr-ser commented Sep 6, 2019

The versions look good. The only thing that comes to mind is I use a spread operator (...) before this line. Might be that the typescript setting of the storybook webpack don't support this feature yet 🤷‍♂️

@cuongdevjs
Copy link

Good. Thanks a lot :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment