Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Created November 24, 2020 03:53
Show Gist options
  • Save AndrewRayCode/a3897c4bdc5141ee6bee3e443c30a460 to your computer and use it in GitHub Desktop.
Save AndrewRayCode/a3897c4bdc5141ee6bee3e443c30a460 to your computer and use it in GitHub Desktop.
const queueIfRunning = originalFn => {
let queuedCall;
let isRunning;
const runner = async (...originalArgs) => {
// If currently running, queue the next run
if (isRunning) {
queuedCall = originalArgs;
} else {
isRunning = true;
await originalFn(...originalArgs);
isRunning = false;
// After the async method finishes, check if someone else is in the
// queue, and if so, kick off another call
if (queuedCall) {
console.log('draining queue!');
const queuedArgs = queuedCall;
queuedCall = null;
await runner(...queuedArgs);
}
}
};
return runner;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment