Created
April 20, 2024 16:12
-
-
Save andersonbosa/2188a6df63d428a40c9bb825acde109b to your computer and use it in GitHub Desktop.
typescript throttle and debounce
This file contains 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
/** | |
* Allow only one call within the time limit | |
* @param { Function } func function to limited | |
* @param { Number } limit time limite in miliseconds | |
*/ | |
export function throttle (func: Function, limit: number) { | |
let inThrottle: boolean | |
return function (this: any) { | |
const args = arguments | |
const context = this | |
if (!inThrottle) { | |
func.apply(context, args) | |
inThrottle = true | |
setTimeout( | |
() => { inThrottle = false }, | |
limit | |
) | |
} | |
} | |
} | |
/** | |
* Returns a function, that, as long as it continues to be invoked, will not | |
* be triggered. The function will be called after it stops being called for | |
* N milliseconds. | |
* | |
* @param { Function } func function to be called | |
* @param { number } wait time in miliseconds to be waited | |
* @param { boolean } immediate trigger the function on the leading edge (true) or trailing (false). | |
*/ | |
export function debounce (func: Function, wait: number, immediate: boolean) { | |
var timeout: number | NodeJS.Timeout | null | |
return function (this: any) { | |
var context = this, | |
args = arguments | |
var later = function () { | |
timeout = null | |
if (!immediate) { | |
return func.apply(context, args) | |
} | |
} | |
var callNow = immediate && !timeout | |
if (timeout) clearTimeout(timeout) | |
timeout = setTimeout(later, wait) | |
if (callNow) { | |
return func.apply(context, args) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment