Implement Throttling
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Question
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:
var assert = require('assert');
function throttle(func, waitTime) {
// fiill in this method
}
let time = 0;
function testThrottle(input) {
const calls = [];
time = 0;
function wrapper(arg) {
calls.push(`${arg}@${time}`);
}
const throttledFunc = throttle(wrapper, 3);
input.forEach((call) => {
const [arg, time] = call.split("@");
setTimeout(() => throttledFunc(arg), time);
});
return calls;
}
expect(testThrottle(["A@0", "B@2", "C@3"])).toEqual(["A@0", "C@3"]);

Solution
Solution
During implementation, the first thing to consider is how we prevent multiple function calls from executing. A very simple way is by using a boolean flag, like isThrottling, to check if we should execute the block. It can be initialized as false, and during the first execution of a function, we can set it to true. Then, the next time the function is invoked, nothing will happen.
function throttle(func, waitTime) {
let isThrottling = false;
return () => {
if (!isThrottling) {
// run the code
func.apply(this);
isThrottling = true;
}
};
}
But of course, this will set the isThrottling flag to true, and all future calls will run into this issue and not execute:
const testCall = throttle(() => console.log("it will run once"));
testCall(); // it will run once
testCall(); // undefined
We'll need to programmatically reset the flag after a certain time. The most obvious way to do this is to use the setTimeout method to flip the boolean after a certain amount of time. Let's add this on.
function throttle(func, waitTime) {
let isThrottling = false;
return () => {
if (!isThrottling) {
// Run the code
func.apply(this);
isThrottling = true;
// Queue up timer to flip the flag so future iterations can occur
function queueTimer() {
setTimeout(() => {
isThrottling = false;
}, waitTime);
}
queueTimer();
}
};
}
We're now at a point where we've wrapped the function in a closure that manipulates the isThrottling flag. The flag will prevent any other calls from executing until a certain time period has passed. Now let's start wrapping this up by making sure the function is indeed invoked again after the waitTime finishes.
One other thing we haven't considered-- what happens in the event that the user invokes the functon during the throttling period, using different arguments? We want to save that call and wait the allotted time before executing. To do this, we'll need to save the new arguments in a savedArgs method.
Please follow the comments to see what's happening:
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
else savedArgs = args;
};
}
One Pager Cheat Sheet
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.