Last active
August 29, 2015 14:20
-
-
Save dikderoy/ec703439f888407eeece to your computer and use it in GitHub Desktop.
Simple Guided Queue
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
/** usage sample | jsfiddle: https://jsfiddle.net/q9g34fzp/10/ **/ | |
function queue() { | |
this.gid = 0; | |
this.q = []; | |
} | |
queue.prototype = { | |
gid: 0, | |
q: [], | |
onProcess: null, | |
afterProcess: null, | |
onEmpty:null, | |
length: function () { | |
return this.q.length; | |
}, | |
push: function (n) { | |
n.id = ++this.gid; | |
this.q.push(n); | |
}, | |
pop: function () { | |
return this.q.shift(); | |
}, | |
remove: function (n) { | |
var oldlen = this.q.length; | |
this.q = this.q.filter(function (c) { | |
if (c.number == n.number && (c.op + n.op) === 0) { | |
//'remove opposite operation' | |
return false; | |
} | |
return true; | |
}); | |
return ((oldlen - this.q.length) < 1); | |
}, | |
process: function () { | |
var n = this.pop(); | |
if (n) { | |
if (this.onProcess) this.onProcess(n, this.processed.bind(this, n)); | |
else this.processed(n); | |
} else if (this.onEmpty) this.onEmpty(); | |
}, | |
processed: function (n) { | |
if(this.afterProcess) this.afterProcess(n); | |
this.process(); | |
} | |
}; | |
function sync(process) { | |
this.q = new queue(); | |
this.q.onEmpty = this.clear.bind(this); | |
this.q.onProcess = (function (n, cb) { | |
this.timer = setTimeout(function () { | |
process(n); | |
cb(); | |
}); | |
}).bind(this); | |
} | |
sync.prototype = { | |
q: null, | |
timer: false, | |
clear: function () { | |
console.log('finalize timer'); | |
this.timer = false; | |
}, | |
run: function (n) { | |
if (this.timer) { | |
console.log('clear timer:' + this.timer); | |
clearTimeout(this.timer); | |
this.timer = false; | |
} | |
if (this.q.remove(n)) { | |
console.log('register changes', n); | |
this.q.push(n); | |
} | |
if (this.timer === false && this.q.length() > 0) { | |
console.log('schedule Q'); | |
this.timer = setTimeout(this.q.process.bind(this.q), 3000); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment