From 2a53887abba882bf7b63aeda8dfa55fdb3ab8792 Mon Sep 17 00:00:00 2001 From: Sin-MacBook Date: Mon, 10 Aug 2020 23:44:20 +0200 Subject: clean this up when home --- src/queue.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/queue.js (limited to 'src/queue.js') diff --git a/src/queue.js b/src/queue.js new file mode 100644 index 0000000..589425e --- /dev/null +++ b/src/queue.js @@ -0,0 +1,40 @@ +class Queue { + constructor() { + this.running = false; + this.queue = []; + } + + add(fn) { + const promise = new Promise(resolve => { + this.queue.push(async () => { + await Promise.resolve(fn()); + resolve(); + }); + + if (! this.running) this.next(); + }); + + return promise; + } + + next() { + this.running = true; + + if (this.queue.length === 0) { + this.running = false; + return; + } + + const fn = this.queue.shift(); + new Promise(resolve => { + // Either fn() completes or the timeout of 10sec is reached + fn().then(resolve); + setTimeout(resolve, 10000); + }).then(() => this.next()); + } +} + +module.exports = { + Queue, + messageQueue: new Queue() +}; -- cgit v1.2.3