AlgoDaily Solution

1function throttle(func, waitTime) {
2  // Set isThrottling flag to false to start
3  // and savedArgs to null
4  let isThrottling = false,
5    savedArgs = null;
6  // Spread the arguments for .apply
7  return function (...args) {
8    // Return a wrapped function
9    // Flag preventing immediate execution
10    if (!isThrottling) {
11      // Actual initial function execution
12      func.apply(this, args);
13      // Flip flag to throttling state
14      isThrottling = true;
15      // Queue up timer to flip the flag so future iterations can occur
16      function queueTimer() {
17        setTimeout(() => {
18          // Stop throttling
19          isThrottling = false;
20          // Queueing up the next invocation after wait time passes
21          if (savedArgs) {
22            func.apply(this, savedArgs);
23            isThrottling = true;
24            savedArgs = null;
25            queueTimer();
26          }
27        }, waitTime);
28      }
29      queueTimer();
30    }
31    // Wait state until timeout is done
32    // Save arguments
33    else savedArgs = args;
34  };
35}

Community Solutions

Community solutions are only available for premium users.

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.

JAVASCRIPT
OUTPUT
Results will appear here.