Batch Collector Time And Size Flush

Collect items into a batch and flush by size threshold or timer whichever fires first for efficient bulk API submission.

JavascriptData Fetching

Code

javascriptsnippet
1 line
export function batchCollector(flush,{maxSize=100,maxWait=5000}={}){let batch=[],timer=null;function schedule(){if(!timer&&maxWait<Infinity)timer=setTimeout(()=>{timer=null;doFlush();},maxWait);}async function doFlush(){if(batch.length===0)return;const cur=batch;batch=[];await flush(cur);}function add(item){batch.push(item);if(batch.length>=maxSize){if(timer){clearTimeout(timer);timer=null;}doFlush();}else schedule();}add.flush=doFlush;add.size=()=>batch.length;return add;}

How it works

The snippet is organized around the functions batchCollector, schedule, doFlush and add.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Watch out for

  • The guard batch.length===0 short-circuits the flow with an early return when its condition holds.

Putting it to use

The primary signature is export function batchCollector(flush,{maxSize=100,maxWait=5000}={})

batchCollector is the public entry point; everything else in the file exists to support it.

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `batchCollector`, `schedule`, `doFlush` at load time.