Skip to content

Instantly share code, notes, and snippets.

@Mortimerp9 Mortimerp9/batch.js
Created Sep 1, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.