Last active
July 15, 2023 15:12
-
-
Save fr-ser/ded7690b245223094cd876069456ed6c to your computer and use it in GitHub Desktop.
Typed debounce function wtih TypeScript
This file contains 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
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); | |
}; | |
}; |
Nope. Works for me. What version of typescript are you using and what compiler (settings)?
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
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 🤷♂️
Good. Thanks a lot :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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[]) {
Any idea?
So I use debounce from https://github.com/chodorowicz/ts-debounce
and everything is fine.