One Pager Cheat Sheet
Throttlingis a technique to limit the number of times a function can execute in any given interval, which is useful for cases likeinfinite scrollingwhere a function needs to be executed only once per user action.- By using a
booleanflag likeisThrottlingand thesetTimeoutmethod, we can create athrottlefunction that executes a given function after a certain amount of time, and save any further calls with different arguments for later invocation.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx35
}function 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); } queueTimer(); } // Wait state until timeout is done // Save argumentsThat's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.