DEV Community

Aurélien Delogu
Aurélien Delogu

Posted on

3 1

Code snippet: a simple rate limiter

This code snippet is different from my previous one: A performant async queue. Even if it works quite the same way.

The big difference is that it runs functions after some wait time, instead of waiting some time after functions have finished to run.

There's also an NPM package: dumb-limiter.

/*
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)
}
}
view raw limiter.ts hosted with ❤ by GitHub

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs