Skip to content

Instantly share code, notes, and snippets.

@djanowski
Created February 1, 2019 16:49
Show Gist options
  • Save djanowski/b664f270b45d10c18def08eb8f2cc288 to your computer and use it in GitHub Desktop.
Save djanowski/b664f270b45d10c18def08eb8f2cc288 to your computer and use it in GitHub Desktop.
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