Skip to content

Instantly share code, notes, and snippets.

@BrianHung
Last active September 30, 2020 11:42
Show Gist options
  • Select an option

  • Save BrianHung/3f6c33771e8295b2cc25bcb4c6db2bc6 to your computer and use it in GitHub Desktop.

Select an option

Save BrianHung/3f6c33771e8295b2cc25bcb4c6db2bc6 to your computer and use it in GitHub Desktop.
Typescript Throttle & Debounce
export function debounce(func: Function, wait: number, immediate = false) {
var timeout;
return function(...args: any[]) {
var context = this;
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
(!immediate) && func.apply(context, args);
}, wait);
(immediate && !timeout) && func.apply(context, args);
};
}
export function throttle(func: Function, interval: number) {
var lastTime = 0;
return function (...args: any[]) {
var now = Date.now().valueOf();
if (now - lastTime >= interval) {
func(args);
lastTime = now;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment