Skip to content

Instantly share code, notes, and snippets.

@Mortimerp9
Created September 1, 2015 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mortimerp9/c33583b4c2bfe9920eb9 to your computer and use it in GitHub Desktop.
Save Mortimerp9/c33583b4c2bfe9920eb9 to your computer and use it in GitHub Desktop.
batch queue calls with javscript
function batch(cb, maxSize, timeout) {
var queue = [];
var timer;
var flushQueue = function() {
cb(queue);
queue = [];
};
return function enQueue(msg) {
if (timer) {
window.clearTimeout(timer);
}
queue.push(msg);
if (queue.length > maxSize) {
flushQueue();
} else {
timer = window.setTimeout(function() {
flushQueue();
}, timeout);
}
};
};
/////////////////
// basic usage
/////////////////
var info = batch(function(a) { console.log(a); }, 10, 1000);
//console.log 0 to 10
// then after timeout console.log 11 to 14
for(var i = 0; i < 15; i++) {
info('msg '+i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment