Created
January 15, 2019 00:40
-
-
Save cauethenorio/52475cadbf71b31c5ffe68124b8ac836 to your computer and use it in GitHub Desktop.
Simple Typescript debounce and throttle
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 debounce(func: (args: IArguments) => any, wait: number, immediate: boolean) { | |
let timeout: number | undefined; | |
return function executedFunction(this: any) { | |
const context: any = this; | |
const args = arguments; | |
const later = () => { | |
timeout = undefined; | |
if (!immediate) { | |
func.apply(context, [args]); | |
} | |
}; | |
const callNow: boolean = immediate && !timeout; | |
clearTimeout(timeout); | |
timeout = window.setTimeout(later, wait); | |
console.log(callNow, timeout); | |
if (callNow) { | |
func.apply(context, [args]); | |
} | |
}; | |
} | |
export function throttle(fn: (args: any[]) => any, wait: number) { | |
let shouldWait = false; | |
return function() { | |
if (!shouldWait) { | |
fn([arguments]); | |
shouldWait = true; | |
setTimeout(() => shouldWait = false, wait); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment