One Pager Cheat Sheet
Throttling
is a technique to limit the number of times a function can execute in any given interval, which is useful for cases likeinfinite scrolling
where a function needs to be executed only once per user action.- By using a
boolean
flag likeisThrottling
and thesetTimeout
method, we can create athrottle
function 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.
xxxxxxxxxx
35
}
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 arguments
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.