Description
You’re given a list of tasks (items) and you want to process them in batches, not all at once — to avoid overloading the system.
Your goal is to implement a function throttle(fn, items, count, time) that:
- Processes the first
count + 1items immediately. - Then, after every
timemilliseconds, processes the next batch ofcount + 1items. - Continues until all items are processed.
- The callback
fnshould be called with each batch.
Function Signature
function throttle(fn, items, count, time)
Parameter | Type | Description |
|---|---|---|
| Function | Function to call for each batch of items |
| Array | Array of items to process |
| Number | Number of items to process per batch (minus one) |
| Number | Time delay (ms) between each batch |
Example
const task = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const count = 5;
throttle(
(batch) => {
console.log(batch);
},
task,
count,
2000
);
Expected Output
[1, 2, 3, 4, 5, 6] // immediately
[7, 8, 9, 10] // after ~2000ms
(The first batch has count + 1 = 6 items, and remaining items are processed after 2 seconds.)
Expected Behavior
- Calls the callback
fnwith the firstcount + 1items immediately. - Calls the callback again after
timems with the next batch. - Stops once all items are processed.
- Does nothing if
itemsis empty or undefined.
Constraints
- Must use recursion or iteration to continue batching.
- Must not use any external libraries.
- Timing should be approximately accurate (±100ms allowed).