Skip to content

Instantly share code, notes, and snippets.

@qpSHiNqp
Created June 3, 2015 11:19
Show Gist options
  • Save qpSHiNqp/1501b5085e3c1185d644 to your computer and use it in GitHub Desktop.
Save qpSHiNqp/1501b5085e3c1185d644 to your computer and use it in GitHub Desktop.
AutoQueue: A queue that runs the given process with an interval if some values are queued and stops if there is no value queued.
/**
* class AutoQueue
*
* queue that runs the given process with an interval if some values are queued
* and stops if there is no value queued.
* 値がqueueされていれば一定間隔で与えられた関数に値を渡し、queueされていなければ黙っているqueue.
*
* @constructor
* @param {Function} func
* @param {number} interval
*/
var AutoQueue = function(func, interval) {
p = Promise.resolve();
/**
* function push
* @param {any} val: value to be passed to the given "func"
*/
this.push = function(val) {
p = p.then(function() {
func(val);
return new Promise(function (resolve) { setTimeout(resolve, interval); });
});
};
};
// Usage example below
var q = new AutoQueue(function(n) {
console.log(n*n); return n*n;
}, 1000);
// queueing
for (var i = 0; i < 10; i++)
q.push(i);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment