Created
March 27, 2021 15:24
-
-
Save steveruizok/dee5dd449a456896829ff8ff4d3ebb94 to your computer and use it in GitHub Desktop.
A typed throttle for Typescript.
This file contains hidden or 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 throttle<T extends (...args: any[]) => any>( | |
fn: T, | |
wait: number | |
) { | |
let inThrottle: boolean, lastFn: any, lastTime: number | |
return function(...a: Parameters<T>): ReturnType<T> { | |
const context = this, | |
args = arguments | |
if (!inThrottle) { | |
lastTime = Date.now() | |
inThrottle = true | |
return fn.apply(context, args) | |
} else { | |
clearTimeout(lastFn) | |
lastFn = setTimeout(function() { | |
if (Date.now() - lastTime >= wait) { | |
lastTime = Date.now() | |
return fn.apply(context, args) | |
} | |
}, Math.max(wait - (Date.now() - lastTime), 0)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment