Skip to content

Instantly share code, notes, and snippets.

@pyrsmk
Last active July 8, 2022 08:53
Show Gist options
  • Save pyrsmk/c1ffd70d8ae8e0f7ca2a5ff8db3ce8a3 to your computer and use it in GitHub Desktop.
Save pyrsmk/c1ffd70d8ae8e0f7ca2a5ff8db3ce8a3 to your computer and use it in GitHub Desktop.
A queue that handles async functions in order with a wait time between each callback.
/*
Usage:
import async_queue from 'async_queue'
const queue = async_queue(<wait_time_in_ms>)
queue(async () => await someSlowAction1())
queue(async () => await someSlowAction2())
*/
export default (waitTime : number) => {
const queue : Array<() => Promise<void>> = []
return (callback : () => Promise<void>) => {
// Add the new callback.
queue.push(async () => {
await callback()
await new Promise(resolve => setTimeout(resolve, waitTime))
// Unqueue and call the next callback.
if (queue.length >= 1) {
queue.shift()
if (queue.length) {
queue[0]()
}
}
})
// Run the current callback directly if it's the only element on the queue.
if (queue.length == 1) {
queue[0]()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment