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.
Code
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===0short-circuits the flow with an earlyreturnwhen 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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.