Last active
November 22, 2018 12:43
-
-
Save enijar/af9ac3ccdecddd0b21cd96a8fbdb6c88 to your computer and use it in GitHub Desktop.
Node server queue idea.
This file contains 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
const TPS = 20; | |
const Queue = { | |
counter: 1, | |
items: {}, | |
/** | |
* Add an item to the queue, with the given func to call | |
* @param {Function} func | |
* @param {Boolean} repeating | |
* @return {Number} | |
*/ | |
add(func, repeating = false) { | |
const id = this.counter++; | |
this.items[id] = {func, repeating, id}; | |
return id; | |
}, | |
/** | |
* Remove an item from the queue with the given id | |
* @param {Number} id | |
*/ | |
remove(id) { | |
if (this.items.hasOwnProperty(id)) { | |
delete this.items[id]; | |
} | |
}, | |
/** | |
* Process items in the queue | |
*/ | |
process() { | |
for (let id in this.items) { | |
// Prevent this item from being processed again | |
if (!this.items.hasOwnProperty(id) || this.items[id].processing) { | |
continue; | |
} | |
// Delete this item when it's scheduled for deletion | |
if (this.items[id].scheduledForDeletion) { | |
delete this.items[id]; | |
continue; | |
} | |
// Let the queue know this item is being processed and | |
// it's scheduled deletion status | |
this.items[id].processing = true; | |
this.items[id].scheduledForDeletion = !this.items[id].repeating; | |
// Don't wait for item's promise to resolve, since this | |
// will create a backlog on the queue | |
(async () => { | |
try { | |
await this.items[id].func.call(null); | |
} catch (err) { | |
// TODO: Handle errors. | |
console.error(err); | |
} | |
this.items[id].processing = false; | |
})(); | |
} | |
} | |
}; | |
(function tick() { | |
setTimeout(tick, 1000 / TPS); | |
Queue.process(); | |
})(); | |
// Example: | |
// Add three items to the queue: 1 normal, 1 async and 1 repeating | |
Queue.add(() => console.info(`[tick] -> ${Date.now()}`)); | |
Queue.add(async () => setTimeout(() => console.info(`[async] -> ${Date.now()}`), 100)); | |
const timeLoop = Queue.add(() => console.info(`[loop] time (loop) -> ${Date.now()}`), true); | |
// Remove the looping item from the queue | |
setTimeout(() => Queue.remove(timeLoop), 500); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment