Skip to content

Instantly share code, notes, and snippets.

@MeyCry
Created May 1, 2020 17:56
Show Gist options
  • Save MeyCry/5f7de38ea3ecd178fa80dab45473592a to your computer and use it in GitHub Desktop.
Save MeyCry/5f7de38ea3ecd178fa80dab45473592a to your computer and use it in GitHub Desktop.
throttle function
/**
* Call fn not more often but and not less then ms
* @param {function} fn - function what need to call not often but and not less then ms
* @param {number} ms - time in milliseconds
* @return (any[]) => void
*/
export const throttle = (fn: (...args: any[]) => void, ms: number = 0) => {
let timeoutId = null;
let lastCall = 0;
return function(...args: any[]): void {
const now = Date.now();
clearTimeout(timeoutId);
if (now - lastCall >= ms) {
lastCall = now;
return fn.apply(this, args);
}
timeoutId = setTimeout(() => {
lastCall = Date.now();
fn.apply(this, args);
}, ms);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment