Throttle

Medium ImportantMicrosoftAmazonGoogleServicenow

Prompt

Throttling is a crucial concept used in JavaScript to optimize the performance of an application. In this challenge, your task is twofold:

  • Part 1: Please provide a detailed explanation of what "throttling" means in the context of JavaScript. Include an explanation of how and why it is useful in JavaScript applications.
  • Part 2: Write a function called throttle in JavaScript.

Solution

Concept Explanation 🧠

Throttling enforces a maximum number of times a function can be called over time.

Let's consider, we have a button in our application that when clicked, makes an API call. The throttle function can restrict the amount of API call. The user may be clicking 10 times a second but we only fire the handler once per second, basically we are not allowing our function to execute more than once every X milliseconds.

If we have not throttled the function which fire on every button click we would have end up making call to API on every click.

Code Explanation 💻

  • We are passing a function fn and a limit limit into the throttle function
  • isThrottled is the variable which we use to keep track of if throttle period has passed or not
  • The first call to our function fn will execute and then we will set the isThrottled to true, also the isThrottled will become false again when our limit period has passed.
  • Now, if throttle is true and limit period has not passed, our function fn during this period will not fire.
  • Once it is passed, the next invocation will fire and the process will repeat.
00:00

Table of Contents