If you folks the simplest explanation on what throttle is, you can refer to this simplest explaination on debounce and throttle.
Write a custom throttle function that will take a function
fn and time
t (milliseconds) as parameters. The function will return the throttled version of
Note: Before diving into the solution, try to solve this problem on your own. Here is a hint: Think closures and setTimeout.
When I am solving any problem, I always like to write the obvious things first. Those things can be found by reading the problem statement itself. There are 2 very obvious things in this question:
- Our custom throttle function is going to return a function.
- That returned function is going to execute the
fnthat we received in the parameters.
Let us start with writing code for these 2 things first
The very first time the throttled function is called, it will execute
fn. And for the next
t seconds, if our throttled function is called, we will ignore and return. Let us see what we can do to achieve this step by step
- We can keep one variable
canCallFunc. If this variable is true we will call
fn. Otherwise, we will return.
- We will initialize
canCallFunwith true because we want to call
fnfor the first time.
- We will have to declare
canCallFuncin the outer function to keep its value across multiple calls. This concept is known as Closures.
- To block further executions of
fn, when we execute it once, we will make
- To unblock function execution again, we will set a timer for time
tand will set
canCallFuncto true at the end.
- if any parameters are passed to our throttled function, we have to pass to
Well, this is a lot of explanation. let us see some actual code. This is what the final version of throttle looks like:
Yay!! This looks like a working solution now. But there are still minor problems with this solution like handling the context of the function. I encourage you to write the code that will handle this condition. And for more interesting questions like this, keep following this series. Until then, Happy Coding!!