Implement Throttling (Medium)
Good afternoon! Here's our prompt for today.
Both debouncing and throttling are intended to enhance a website's performance. They accomplish this primarily by limiting the number of times a function can execute.
In the case of throttling, the exact definition is that it's a technique where a function can be executed only once in any given time interval-- regardless of how many times the user fires the event.
When is this useful? Consider the example of infinite scroll. Each time the user scrolls to the bottom of the page, we'll want to execute a function to grab the next list of resources to display. However, it's really easy for a user to scroll back up a bit and then try again, possibly several times, if the results don't load fast enough. If we throttle that call, we won't make unnecessary, expensive network calls.
Please use the following to test your code, comments in-line:
1var assert = require('assert');
2
3function throttle(func, waitTime) {
4  // fiill in this method
5}
6
7let time = 0;
8
9function testThrottle(input) {
10  const calls = [];
11  time = 0;
12
13  function wrapper(arg) {
14    calls.push(`${arg}@${time}`);
15  }
16
17  const throttledFunc = throttle(wrapper, 3);
18  input.forEach((call) => {
19    const [arg, time] = call.split("@");
20    setTimeout(() => throttledFunc(arg), time);
21  });
22  return calls;
23}
24
25expect(testThrottle(["A@0", "B@2", "C@3"])).toEqual(["A@0", "C@3"]);
xxxxxxxxxxfunction throttle(func, waitTime) {  // Set isThrottling flag to false to start  // and savedArgs to null  let isThrottling = false,    savedArgs = null;  // Spread the arguments for .apply  return function (args) {    // Return a wrapped function    // Flag preventing immediate execution    if (!isThrottling) {      // Actual initial function execution      func.apply(this, args);      // Flip flag to throttling state      isThrottling = true;      // Queue up timer to flip the flag so future iterations can occur      function queueTimer() {        setTimeout(() => {          // Stop throttling          isThrottling = false;          // Queueing up the next invocation after wait time passes          if (savedArgs) {            func.apply(this, savedArgs);            isThrottling = true;            savedArgs = null;            queueTimer();          }        }, waitTime);