Published on

Limiting the Execution of Promises or Functions in JavaScript

Authors

Sometimes we want to limit the execution of function calls (especially when working with external API)

p-throttle NPM package might be a good choice for these cases.

With this package, we can easily throttle the execution of a promise-returning function (or even a regular function)

Dependency

npm install p-throttle

Snippet

// Based on p-throttle's README example
import pThrottle from 'p-throttle';

const throttle = pThrottle({
	limit: 1,
	interval: 1000
});

const fetchUser = async () => {
	const response = await fetch('https://randomuser.me/api/');
	return response.json();
};

const throttledFetchUser = throttle(fetchUser)

throttledFetchUser()
throttledFetchUser() // This will be debounced

Check out their docs for more snippets and details about its options.

Happy throttling Promises!