Skip to content

Instantly share code, notes, and snippets.

@adriancmiranda
Forked from ca0v/debounce.ts
Created December 22, 2023 20:47
Show Gist options
  • Save adriancmiranda/93cf021e50cd507d204958cb36755d37 to your computer and use it in GitHub Desktop.
Save adriancmiranda/93cf021e50cd507d204958cb36755d37 to your computer and use it in GitHub Desktop.
Typescript Debounce
// ts 3.6x
function debounce<T extends Function>(cb: T, wait = 20) {
let h = 0;
let callable = (...args: any) => {
clearTimeout(h);
h = setTimeout(() => cb(...args), wait);
};
return <T>(<any>callable);
}
// usage
let f = debounce((a: string, b: number, c?: number) => console.log(a.length + b + c || 0));
f("hi", 1, 1);
f("world", 1);
@adriancmiranda
Copy link
Author

export type Action = (...args: any[]) => any

export function throttle<Callback extends Action>(callback: Callback, waitFor: number) {
    const now = () => new Date().getTime()
    const resetStartTime = () => (startTime = now())
    let timeout: number
    let startTime: number = now() - waitFor

    return (...args: Parameters<Callback>): Promise<ReturnType<Callback>> =>
        new Promise((resolve) => {
            const timeLeft = startTime + waitFor - now()
            if (timeout) {
                window.clearTimeout(timeout)
            }
            if (startTime + waitFor <= now()) {
                resetStartTime()
                resolve(callback(...args))
            } else {
                timeout = window.setTimeout(() => {
                    resetStartTime()
                    resolve(callback(...args))
                }, timeLeft)
            }
        })
}

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