Created
August 21, 2024 13:23
-
-
Save agazso/77729b763668034a7e65d0a95c574334 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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