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:
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.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:
throttle
function that limits how frequently an API call can be made.Hints:
setTimeout
or timestamps to track the time between calls.closures
to keep track of the throttle state between function calls.Bonus:
throttle
function to accept an option that triggers the first call immediately, but enforces the throttle after that.