Categories
interview

Throttling function calls with a Queue in Javascript (ES6)

The following ES6 Javascript code, helps to throttle function calls without discarding them. It uses a queue to keep track of all the function calls. We can use the reset method to reset the queue and the setTimeout() method.

const throttle = (fn, delay) => {
  let timeout;
  let noDelay = true;
  let queue = [];
  const start = () => {
    if (queue.length) {
      const first = queue.shift();
      fn.apply(first.context, first.arguments);
      timeout = setTimeout(start, delay);
    } else {
      noDelay = true;
    }
  };

  const ret = (...rest) => {
    queue.push({
      context: this,
      arguments: [...rest]
    });
    if (noDelay) {
      noDelay = false;
      start();
    }
  };

  ret.reset = () => {
    clearTimeout(timeout);
    queue = [];
  };
  return ret;
};

/* Usage */

const print = (number) => {
  console.log(`Hello World! ${number}`);
}

const test = throttle(print, 3000);

test(1);
test(2);
test(3);

// test.reset(); This will clear the queue and hence the above test case will only output the first line.
// Output:
// Hello World! 1
// Hello World! 2
// Hello World! 3

Demo