Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Throttle an async (promise-returning) function in JavaScript/Node.js
// Throttles an async function.
function throttleAsync(fn, wait) {
let lastRun = 0;
let currentRun = null;
async function throttled(...args) {
if (currentRun)
return currentRun;
const currentWait = lastRun + wait - Date.now();
const shouldRun = currentWait <= 0;
if (shouldRun) {
lastRun = Date.now();
currentRun = fn(...args);
const value = await currentRun;
currentRun = null;
return value;
} else {
return await new Promise(function(resolve) {
setTimeout(function() {
resolve(throttled(...args));
}, currentWait);
});
}
}
return throttled;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.