// DECLARE DEBOUNCE FUNCTION
debounce = <T extends (...args: any[]) => any>(
callback: T,
waitFor: number
) => {
let timeout: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>): ReturnType<T> => {
let result: any;
timeout && clearTimeout(timeout);
timeout = setTimeout(() => {
result = callback(...args);
}, waitFor);
return result;
};
};
// USE DEBOUNCE FUNCTION
debounce((data) => {
// DO THE JOB
this.job(data);
}, 50)({"data":"myData"});
const debounce = <F extends (...args: any[]) => any>(
func: F,
waitFor: number
) => {
let timeout: ReturnType<typeof setTimeout> | null = null
const debounced = (...args: Parameters<F>) => {
if (timeout !== null) {
clearTimeout(timeout)
timeout = null
}
timeout = setTimeout(() => func(...args), waitFor)
}
return debounced as (...args: Parameters<F>) => ReturnType<F>
}
// Usage
const debounceCallback = () => {
console.log('Debounce')
}
debounce<typeof debounceCallback>(debounceCallback, 500)
// Not the best, but doesn't have <any> types,
// the `let timer` has, but the eslint won't complicate
export default function (fn: () => void, delay = 300) {
let timer
return (() => {
clearTimeout(timer)
timer = setTimeout(() => fn(), delay)
})()
}