Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Last active December 18, 2015 20:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jeffreyiacono/5844008 to your computer and use it in GitHub Desktop.
generic queue that applies the passed operation to each element, separating each call out by the specified throttle
function Queue(config) {
this.throttle = (typeof config['throttle'] !== "undefined") ? config['throttle'] : 2000;
this.elements = config['elements'];
this.operation = config['operation'];
this.interval_id = null;
return this;
}
Queue.prototype.process = function() {
var self = this;
this.interval_id = window.setInterval(function() {
self.operation(self.elements.shift());
if (self.elements.length <= 0) { self.halt(); }
}, this.throttle);
}
Queue.prototype.halt = function() {
clearInterval(this.interval_id);
this.log("halted interval " + this.interval_id);
this.interval_id = null;
}
Queue.prototype.log = function(msg) {
console.log("[" + new Date + "] " + msg);
}
@jeffreyiacono
Copy link
Author

ex:

var elements = [1, 2, 3, 4];
var operation = function(element) {
    console.log("[" + new Date + "] element " + element + " times 2 = " + element * 2);
}

q = new Queue({elements: elements, operation: operation});
q.process();
/*
output ...
[Sun Jun 23 2013 14:07:06 GMT-0700 (PDT)] element 1 times 2 = 2
[Sun Jun 23 2013 14:07:08 GMT-0700 (PDT)] element 2 times 2 = 4
[Sun Jun 23 2013 14:07:10 GMT-0700 (PDT)] element 3 times 2 = 6
[Sun Jun 23 2013 14:07:12 GMT-0700 (PDT)] element 4 times 2 = 8
[Sun Jun 23 2013 14:07:12 GMT-0700 (PDT)] halted interval 3 
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment