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 + 1 items immediately.
  • Then, after every time milliseconds, processes the next batch of count + 1 items.
  • Continues until all items are processed.
  • The callback fn should be called with each batch.

Function Signature

function throttle(fn, items, count, time)

Parameter

Type

Description

fn

Function

Function to call for each batch of items

items

Array

Array of items to process

count

Number

Number of items to process per batch (minus one)

time

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 fn with the first count + 1 items immediately.
  • Calls the callback again after time ms with the next batch.
  • Stops once all items are processed.
  • Does nothing if items is 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).