Skip to content

Instantly share code, notes, and snippets.

@cauethenorio
Created January 15, 2019 00:40
Show Gist options
  • Save cauethenorio/52475cadbf71b31c5ffe68124b8ac836 to your computer and use it in GitHub Desktop.
Save cauethenorio/52475cadbf71b31c5ffe68124b8ac836 to your computer and use it in GitHub Desktop.
Simple Typescript debounce and throttle
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