Skip to content

Instantly share code, notes, and snippets.

@beautyfree
Created January 30, 2018 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beautyfree/2f974c10966da64887c146c4e075c458 to your computer and use it in GitHub Desktop.
Save beautyfree/2f974c10966da64887c146c4e075c458 to your computer and use it in GitHub Desktop.
Rate limit for api requests from https://github.com/axios/axios/issues/230
function promiseDebounce(fn, delay, count) {
var working = 0, queue = []
function work() {
if ((queue.length === 0) || (working === count)) return
working++
new Promise(function(resolve, reject){
setTimeout(function(){
working--
work()
}, delay)
})
var next = queue.shift()
next[2](fn.apply(next[0], next[1]))
}
return function debounced() {
var args = arguments
return new Promise(function(resolve){
queue.push([this, args, resolve])
if (working < count) work()
}.bind(this))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment