Skip to content

Instantly share code, notes, and snippets.

@lansana
Created March 30, 2018 17:16
Show Gist options
  • Save lansana/d787af78c99c87e7d9032c7e729c74dc to your computer and use it in GitHub Desktop.
Save lansana/d787af78c99c87e7d9032c7e729c74dc to your computer and use it in GitHub Desktop.
Batch push items into a list
batch(items: any[], count: number, interval: number, iteratee: (item: any, index: number) => void) {
const len = items ? items.length : 0;
// If the count is gte the total amount, just loop through and add
// them all and don't bother batching.
if (count >= len) {
for (let i = 0; i < len; i++) {
iteratee(items[i], i);
}
return;
}
let index = 0;
const _batch = () => {
const timeout = setTimeout(() => {
let batchItems: any[];
if (index > 0) {
batchItems = notifications.slice(index, count + index);
} else {
batchItems = notifications.slice(0, count);
}
const batchItemsLen = batchItems.length;
if (batchItemsLen > 0) {
index += count;
for (let i = 0; i < batchItemsLen; i++) {
iteratee(batchItems[i], i);
}
return _batch();
}
clearTimeout(timeout);
}, interval);
};
_batch();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment