Created
February 20, 2021 06:17
-
-
Save ExcitedSpider/3c201df72397cf8f9cfba059f6a9051c to your computer and use it in GitHub Desktop.
simple debounce & throttle
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
export const debounce: <T extends []>(fn: (...args: T) => void, wait: number) => (...args: T) => void = (fn, wait) => { | |
let timeout = -1; | |
return (...args) => { | |
if (timeout !== -1) clearTimeout(timeout); | |
timeout = setTimeout(() => { | |
fn(...args); | |
}, wait); | |
}; | |
}; |
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
export const throttle: <T extends []>(fn: (...args: T) => void, wait: number) => (...args: T) => void = (fn, wait) => { | |
let canRun = true; | |
return (...args) => { | |
if (!canRun) { | |
return; | |
} | |
fn(...args); | |
canRun = false; | |
setTimeout(() => { | |
canRun = true; | |
}, wait); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment