Skip to content

Instantly share code, notes, and snippets.

@adalberth
Last active November 20, 2018 19:16
Show Gist options
  • Save adalberth/5fb0596de39c0dafc8785b2d46a44557 to your computer and use it in GitHub Desktop.
Save adalberth/5fb0596de39c0dafc8785b2d46a44557 to your computer and use it in GitHub Desktop.
Queue
export default class Queue {
constructor () {
this.id = this.newid()
this.queue = []
}
add (callback) {
this.queue.push({
id: this.id,
callback
})
}
run (complete=false) {
this.loop(this.id, complete)
}
loop (id, complete) {
if(id !== this.id) return
const item = this.queue.splice(0, 1)[0] || false
if (item) {
const done = () => this.loop(id, complete)
item.callback(this.guard(item.id, done))
} else if (complete) {
complete()
}
}
guard (id, done) {
return callback => id === this.id && callback(done)
}
flush () {
this.id = this.newid()
this.queue = []
}
newid () {
return Date.now() + Math.random().toString(36).substring(2, 15)
}
}
/*
const q = new Queue()
// Sync
q.add(guard => guard(done => {
// do stuff
done()
}))
// Async
// Here the gaurd is used, so that the current process
// isnt run if the current queue has been flushed
q.add(guard => {
setTimeout(() => {
guard(done => {
// do stuff
done()
})
}, 1000)
})
// Run
q.run(() => {
// Callback
// when the queue is done
})
// Flush the queue
// Flushed the entire queue
q.flush()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment