Skip to content

Instantly share code, notes, and snippets.

@routevegetable
Last active April 10, 2020 15:53
Show Gist options
  • Save routevegetable/a5a33c9f4aa5cb61ee9495abcc894a64 to your computer and use it in GitHub Desktop.
Save routevegetable/a5a33c9f4aa5cb61ee9495abcc894a64 to your computer and use it in GitHub Desktop.
No idea if this works
function AsyncRateLimiter() {
/* Operation is in progress */
this.doingThing = false;
/* Next operation to do after this one */
this.nextFn = false;
}
AsyncRateLimiter.prototype.submit = function(fn) {
var instance = this;
if(!instance.doingThing) {
instance.doingThing = true;
function doNext() {
/* Do the next thing if there is one */
if(instance.nextFn) {
var p = instance.nextFn();
instance.nextFn = null;
p.then(doNext);
} else {
instance.doingThing = false;
}
}
/* Do it immediately */
fn().then(doNext);
} else {
/* Do it next, dropping whatever was there */
instance.nextFn = fn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment