Codetive
Sign In
Coding challenges as of now are only available on desktop
On mobile you can try our quiz
Quiz
We are working hard to bring coding challenges with editor on mobile 💚

Throttle API Calls

Objective: Implement a function that throttles API calls, make sure that a function is only executed once within a specified time window, even if it's triggered multiple times.

Instructions:

  1. Create a function named throttle that limits how often an API call is made. If the function is called again within the time window, it should ignore the subsequent calls until the window has passed.
  2. The function should take two arguments:
    • The API call function to throttle.
    • The throttle time in milliseconds (e.g., 2000 ms for a 2-second throttle).
  3. Ensure the function can handle multiple calls but only executes the API call once per time window.

Example Usage:

const throttledApiCall = throttle(apiCall, 2000);
 
button.addEventListener('click', throttledApiCall); 
// Only allows the API call once every 2 seconds, even if the button is clicked multiple times.

Requirements:

  • Create a throttle function that limits how frequently an API call can be made.
  • The function should ignore subsequent calls during the window and only execute after the window has passed.
  • Ensure the API call function is executed at least once after the throttle window resets.

Hints:

  1. Use setTimeout or timestamps to track the time between calls.
  2. Consider using closures to keep track of the throttle state between function calls.

Bonus:

  1. Allow the throttle function to accept an option that triggers the first call immediately, but enforces the throttle after that.
Browser
Console
Tests
Soon