What is Throttling?

RMAG news

Throttling is a technique used to limit the rate at which a function is called. Throttling transforms a function such that it can only be called once in a specific interval of time.

First understand what we want to achieve with throttling:

Call the function immediately the first time.
After each call, prevent the function from being called again for a certain time period.
Once that time period has passed, the function can be called again.
To do all this, let’s first create a helper function that will return a throttled function:

Next, we’ll declare a variable timeout that will be initialized only once in the outer function (that is the throttle() function). The setTimeout method returns a unique timeout id that we can use to identify a timeout. We’ll assign the current timeout id to timeout.

function throttle(func, delay) {
let timeout=null
return () => {
if(!timeout) {
func()
timeout=setTimeout(() => {
// do something
}, delay)
}
}
}

Implement Throttling using a React.js Custom Hook

We’ll write the throttling logic inside a custom hook. Since you may need throttling in multiple places in your application, it is recommended to put the logic inside a custom hook.

Create a new folder called custom-hooks. Inside it, create a file useThrottle.js. Inside the file, create and export new function useThrottle(). The method should take a function and delay as parameters and return the throttled function.

const useThrottle = (func, delay) => {
let timeout = null;
return (…args) => {
if (timeout) {
return;
}
func(…args);
timeout = setTimeout(() => {
timeout = null;
}, delay);
};
};

export default useThrottle;

Now, inside the App component, call this method and pass the click handler handleClick() and a delay of 1000ms.

const handleClickThrottled = useThrottle(handleClick, 1000);

We’ll use this function as the event handler for our button.

<button onClick={handleClickThrottled}>Click Me</button>