Created
September 1, 2015 23:08
-
-
Save Mortimerp9/c33583b4c2bfe9920eb9 to your computer and use it in GitHub Desktop.
batch queue calls with javscript
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
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