Typescript debounce function not calling function passed as parameter
This is intended as a supplement to Saveli Tomac's excellent answer.
In the comments I said I didn't think that implementation was particularly good. In particular it has two problems:
- It doesn't have an immediate option. Most debounce implementations in the wild (including the one you linked in your question) have this.
- The returned function ignores the
this
value.
Here's an example that fixes these:
const debounce = (n: number, fn: (...params: any[]) => any, immed: boolean = false) => {
let timer: number | undefined = undefined;
return function (this: any, ...args: any[]) {
if (timer === undefined && immed) {
fn.apply(this, args);
}
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), n);
return timer;
}
};
Typescript Playground
How do you use your debounce
function? I prepare fiddle, you can check working solution here
function debounce<Params extends any[]>(
func: (...args: Params) => any,
timeout: number,
): (...args: Params) => void {
let timer: NodeJS.Timeout
return (...args: Params) => {
clearTimeout(timer)
timer = setTimeout(() => {
func(...args)
}, timeout)
}
}
function test(message) {
alert(message);
}
const debouncedTest = debounce(test, 2000);
debouncedTest('message');
Well, it's not typescript troubles