Skip to content

Instantly share code, notes, and snippets.

@zazaulola
Last active October 11, 2021 22:50
Show Gist options
  • Save zazaulola/8006177ec74909893835a4980761d6d9 to your computer and use it in GitHub Desktop.
Save zazaulola/8006177ec74909893835a4980761d6d9 to your computer and use it in GitHub Desktop.
Queue, thread, stack, task, job, flow, stream
const Queue = () => {
let idle = true;
const stack = [],
fx = (...job) => {
stack.push(...job);
if(idle)
(async () => {
idle = false;
while(stack.length)
await stack.shift()();
idle = true;
})();
};
Object.defineProperty(fx,'pending',{get: ()=>stack.length});
return fx;
};
// ======= Test ==========
const wait = ms => new Promise(res => setTimeout(res,ms));
const Job = id => async ()=>{
console.log('Job started: ' + id);
await wait(1000);
console.log('Job finished: ' + id);
};
const queue = Queue();
queue(Job(1));
queue(Job(2));
queue(Job(3),Job(4),Job(5));
queue(Job(6));
queue(Job(7),Job(8));
console.log(queue.pending);
setTimeout(()=>console.log(queue.pending),2500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment