Skip to content

Instantly share code, notes, and snippets.

@pyrsmk
Created July 8, 2022 09:41
Show Gist options
  • Save pyrsmk/4c0082fa69b1f50e0e489a787bc9c606 to your computer and use it in GitHub Desktop.
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.
/*
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