Last active
April 10, 2020 15:53
-
-
Save routevegetable/a5a33c9f4aa5cb61ee9495abcc894a64 to your computer and use it in GitHub Desktop.
No idea if this works
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
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