Skip to content

Instantly share code, notes, and snippets.

@agazso
Created August 21, 2024 13:23
Show Gist options
  • Select an option

  • Save agazso/77729b763668034a7e65d0a95c574334 to your computer and use it in GitHub Desktop.

Select an option

Save agazso/77729b763668034a7e65d0a95c574334 to your computer and use it in GitHub Desktop.
export function createQueue(options?: Partial<{ maxItems?: number, noRun?: boolean }>) {
const queue: QueueAction[] = []
let isPendingAction = false
const maxItems = options?.maxItems
return {
async enqueue(action: QueueAction) {
if (maxItems && queue.length === maxItems) {
queue.shift() // throw away
}
queue.push(action)
if (options?.noRun) {
return
}
await this.run()
},
async run() {
if (isPendingAction) {
return
}
try {
isPendingAction = true
while (queue.length > 0) {
const action = queue.shift()
if (!action) {
break
}
await action()
}
} catch (e) {
console.error({ e })
} finally {
isPendingAction = false
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment