How to throttle

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2024-03-05

I wanted to do some throttling - i.e. to control how often something a function was called in JavaScript. The goal was to avoid exceeding a rate limit. How can I implement this ?

The following code does the job:

const throttle = (fn, delay) => {
  let last = 0

  return (..args) => {
    const now = new Date().getTime()
    if (now - last < delay) {
      return;
    }
    last = now;
    return fn(...args);
  }
}

// Usage
element.onClick(throttle(hitApi, 3000))

Here's how it works

The throttle function takes the original hitApi function and wraps it, spitting out another function that selectively calls the hitApi function depending on whether or not long enough has passed.

(As such the returned function calls the original function.)

The time of the last execution is stored in the variable last. It is set to 0 with the call to throttle. While the returned function can be called as often you like, the last state is shared between them all.