Created
July 8, 2022 09:41
-
-
Save pyrsmk/4c0082fa69b1f50e0e489a787bc9c606 to your computer and use it in GitHub Desktop.
A simple rate limiter that waits for N milliseconds before running the next callback.
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
/* | |
How to use: | |
import limiter from './limiter' | |
const limit = limiter(<wait_time_in_ms>) | |
limit(() => console.log('foo')) | |
limit(async () => console.log('bar')) | |
*/ | |
export default (interval : number) => { | |
if (interval <= 0) { | |
throw new Error("'interval' must be a positive integer") | |
} | |
const queue : Array<() => (void | Promise<void>)> = [] | |
const unqueue = () => { | |
const callback = queue.shift() | |
if (callback) { | |
callback() | |
} | |
} | |
setInterval(unqueue, interval) | |
return (callback : () => (void | Promise<void>)) => { | |
queue.push(callback) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment