Created
February 1, 2019 16:49
-
-
Save djanowski/b664f270b45d10c18def08eb8f2cc288 to your computer and use it in GitHub Desktop.
Throttle an async (promise-returning) function in JavaScript/Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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