Created
May 1, 2020 17:56
-
-
Save MeyCry/5f7de38ea3ecd178fa80dab45473592a to your computer and use it in GitHub Desktop.
throttle function
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
/** | |
* 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